package com.iris.live.services.services.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import com.iris.live.services.common.*;

import com.iris.live.services.common.reconsitution.*;
import com.iris.live.services.common.reconsitution.HttpTools;
import com.iris.live.services.data.models.*;
import com.iris.live.services.data.repositories.*;
import com.iris.live.services.interceptors.SessionInterceptor;
import com.iris.live.services.models.PageData;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.models.boutiquedocking.StockDetailParam;
import com.iris.live.services.models.boutiquedocking.StockParam;
import com.iris.live.services.models.boutiquedocking.StockResult;
import com.iris.live.services.services.ApprovalService;
import com.iris.live.services.services.BrandService;
import com.iris.live.services.services.SetService;
import com.iris.live.services.vo.si.SiImportVo;
import com.iris.live.services.vo.si.SibmbsImportVo;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.interceptor.TransactionInterceptor;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional

public class SetServiceImpl implements SetService {
    private static final Logger logger = LoggerFactory.getLogger(SetServiceImpl.class);
    @Autowired
    报价付款详细Repository 报价付款详细repository;
    @Autowired
    Lsh经销商表Repository lsh经销商表Repository;
    @Autowired
    顾客记录汇总Repository 顾客记录汇总Repository;
    @Autowired
    private VirtualStockModelRepository virtualStockModelRepository;
    @Autowired
    private SetRepository setRepository;
    @Autowired
    private RoleItemRepository roleItemRepository;
    @Autowired
    private AttachmentPolicyRepository attachmentPolicyRepository;
    @Autowired
    private Itask基础设置Repository itaskRepository;
    @Autowired
    private 用户Repository userRepository;
    @Autowired
    private Lsh随车项目设置repository lshCarProRepository;
    @Autowired
    private PushApprovalWorkFlowRepository2 pushWorkFlowRepository;
    @Autowired
    private 调入付款详单Repository callInRepository;
    @Autowired
    private 调出收款详单Repository callOutRepository;
    @Autowired
    private DealerAttachmentPolicyRepository dApilicyRepository;
    @Autowired
    private Lsh市场设置Repository lshMarketSetRepository;
    @Autowired
    private IncomeAdjustmentRepository inAdjustmentRepository;
    @Autowired
    private 销售收款单Repository saleReceiptRepository;
    @Autowired
    private 报价付款详细Repository paymentDetailRepository;
    @Autowired
    private 财务详单Repository financialDetailsRepository;
    @Autowired
    private 销售项目设置Repository saleItemRepository;
    @Autowired
    private PushApprovalItemSettingRepository pushApprovalItemSettingRepository;
    @Autowired
    private Lsh库存表Repository lsh库存表Repository;
    @Autowired
    private CarTransferLogRepository carTransferLogRepository;
    @Autowired
    private 财务开票Repository 财务开票Repository;
    @Autowired
    private 报价单表Repository 报价单表Repository;
    @Autowired
    private 报价交车表Repository 报价交车表Repository;
    @Autowired
    private Lsh消息Repository lsh消息Repository;
    @Autowired
    private MessageSettingRepository messageSettingRepository;
    @Autowired
    private Lsh车型Repository lsh车型Repository;
    @Autowired
    private 报价订单表Repository 报价订单表Repository;
    @Autowired
    private 顾客试驾记录Repository repository顾客试驾记录;

    @Autowired
    private IteminfoRepository Iteminforepository;

    @Autowired
    private Itask基础设置Repository itask基础设置Repository;

    @Autowired
    private SNPSettingRepository snpSettingRepository;

    @Autowired
    private 顾客进店记录表Repository repository顾客进店记录表;

    @Autowired
    private SisettingRepository sisettingRepository;
    @Autowired
    private SibmbsSettingRepository sibmbsSettingRepository;

    //SI数据查询新增
    @Autowired
    private 报价保险表Repository 报价保险表Repository;
    @Autowired
    private 报价金融表Repository 报价金融表Repository;
    @Autowired
    private Lsh金融申请附属Repository lsh金融申请附属Repository;
    @Autowired
    private 报价精品表Repository 报价精品表Repository;
    @Autowired
    private 报价精品详细表Repository 报价精品详细表Repository;
    @Autowired
    private 报价五星延保Repository 报价五星延保Repository;
    @Autowired
    private 报价随车表Repository 报价随车表Repository;
    @Autowired
    private 报价付款详细Repository 报价付款详细Repository;
    @Autowired
    private PermitCodeRepository permitCodeRepository;
    @Resource
    private ApprovalService approvalService;
    @Resource
    private TBoutiqueCallCheckRepository tBoutiqueCallCheckRepository;

    @Autowired
    private Environment env;

    @Autowired
    private BrandService brandService;

    @Resource
    private 用户Repository 用户Repository;

    @Override
    public List getItaskSetItems(String permit, String setItem) {
        return setRepository.getItaskSetItems(permit, setItem);
    }

    @Override
    public List getRootByRole(String permit) {
        List<IteminfoModel> alllist = Iteminforepository.findAll();
        List mingzi = new ArrayList();
        for (int i = 0; i < alllist.size(); i++) {
            IteminfoModel sons = alllist.get(i);
            mingzi.add(sons.getItemName());
        }
        return setRepository.getRootByRole(permit, mingzi);
    }

    @Override
    public List getAllLshRole() {
        return setRepository.getAllLshRole();
    }

    @Override
    public boolean insertRoleItem(RoleItemModel roleItem) {
        try {
            roleItemRepository.save(roleItem);
        } catch (Exception e) {
            logger.error("运行异常。", e);
            return false;
        }
        return true;
    }

    @Override
    public PageData getDepositList(inOutAccountRequest accRequset, String permit) {
        return setRepository.getDepositList(accRequset, permit);
    }

    @Override
    @Transactional
    public ResultData saveDepositStatus(inOutAccountRequest re, String permit) {
        ResultData rd=new ResultData();
        rd.setResult("true");
        rd.setMessage("修改成功");
        //("UPDATE 报价付款详细Model u SET u.实付金额 = ?1 ,u.更新账号=?2 WHERE u.付款事由 = ?3 AND u.报价编号 = ?4 ")
        报价单表Model 报价单表Model = 报价单表Repository.findBy报价编号(Integer.parseInt(re.id));
        //同时修改最新的一条财务数据
        报价单表Model 报价单表Model2 = 报价单表Repository.findBy初始报价编号(报价单表Model.get初始报价单号()).get(0);

        报价付款详细Model  updateModel=报价付款详细repository.getTotals(Integer.parseInt(re.id),re.carSaleType);
        if(updateModel!=null){
            报价付款详细repository.updateNewCarSaleMoneys(updateModel.get应付金额(),
                    permit,re.carSaleType,Integer.parseInt(re.id));
        }else{
            报价付款详细Model  insertModel=new 报价付款详细Model();
            insertModel.set应付金额("0");
            insertModel.set应付金额("0");
            insertModel.set付款事由(re.carSaleType);
            insertModel.set更新账号(permit);
            insertModel.set更新时间(new Timestamp(System.currentTimeMillis()));
            insertModel.set报价编号(Integer.parseInt(re.id));
            报价付款详细repository.save(insertModel);
            rd.setMessage("传入的报价编号在付款详细中不存在,进行插入操作");
        }
        if(报价单表Model2!=null){
            报价付款详细Model  MaxupdateModels=报价付款详细repository.getTotals(Integer.parseInt(re.id),re.carSaleType);
            if(MaxupdateModels!=null){
                报价付款详细repository.updateNewCarSaleMoneys(MaxupdateModels.get应付金额(),
                        permit,re.carSaleType,MaxupdateModels.get报价编号());
            }
        }

        return  rd;
    }


    @Override
    public boolean deleteAllRoleItem(String permit) {
        try {
            roleItemRepository.deleteRoleItemByPermit(permit);
        } catch (Exception e) {
            logger.error("运行异常。", e);
            return false;
        }
        return true;
    }

    @Override
    public PageData getAllCarPolicy(GetCarPolicyRequest carPolicyReq) {
        return setRepository.getAllCarPolicy(carPolicyReq);
    }

    @Override
    public int saveCarPolicy(List<AttachmentPolicyModel> policyModelList) {
        int success = 0;
        for (AttachmentPolicyModel policyModel : policyModelList) {
            try {
                List<AttachmentPolicyModel> model =
                        attachmentPolicyRepository.findPolicyBYSiProgramCodeEnglishAndPermit(policyModel.getSiProgramCodeEnglish(), policyModel.getPermit());

                if (model == null || model.size() == 0) {
                    attachmentPolicyRepository.save(policyModel);
                }

                success++;
            } catch (Exception e) {
                logger.error("厂家随车保存异常:", e);
                LogFactory.getLog(SetServiceImpl.class).info(e.getStackTrace());
            }
        }
        return success;
    }

    @Override
    public boolean deleteCarPolicy(String engCode, String permit) {
        try {
            attachmentPolicyRepository.deleteByProCodeEngAndPermit(engCode, permit);
        } catch (Exception e) {
            logger.error("删除厂家随车政策异常:", e);
            LogFactory.getLog(SetServiceImpl.class).info(e.getStackTrace());
            return false;
        }
        return true;
    }

    @Override
    public List getAllCarDetailInfo() {
        return setRepository.getAllCarDetailInfo();
    }

    @Override
    public List getAllCarTypeInfo() {
        return setRepository.getAllCarTypeInfo();
    }

    @Override
    public List getCarColorByCarType(String carParam) {
        return setRepository.getCarColorByCarType(carParam);
    }

    @Override
    public int saveCarPolicyWithDel(List<AttachmentPolicyModel> policyModelList) {
        int success = 0;
//        int i = 0;
        for (AttachmentPolicyModel policyModel : policyModelList) {
            try {
                /*if (i == 0) {*/
                    attachmentPolicyRepository.deleteByItemNumAndPermit(
                            policyModel.getItemNumber(), policyModel.getPermit(), policyModel.getSiProgramCodeEnglish());
                  /*  i++;
                }*/

                attachmentPolicyRepository.save(policyModel);
                success++;
            } catch (Exception e) {
                logger.error("厂家随车数据拆解保存出错:", e);
                logger.info("厂家随车数据拆解保存出错:",e.getMessage());
            }
        }
        return success;
    }

    @Override
    public List getDisplayFlowInfo(String permit, Date startDate, Date endDate) {
        List list = setRepository.getDisplayFlowInfo(permit, startDate, endDate);
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Map m = (Map) list.get(i);
                Integer id = (Integer) (m.get("进店编号"));
                //查询到试驾车和车型表
                String carDetails = "";
                List<顾客试驾记录Model> modelList = repository顾客试驾记录.findBy进店编号(id);
                String startTime = "";//试驾开始时间
                String endTime = "";//试驾结束时间
                String totalTime = "";//试驾时长
                for (int j = 0; j < modelList.size(); j++) {
                    if (j > 0) {
                        startTime = startTime + ";";
                        endTime = endTime + ";";
                        totalTime = totalTime + ";";
                        carDetails = carDetails + ";";
                    }

                    顾客试驾记录Model model试驾记录 = modelList.get(j);
                    Integer carId = model试驾记录.get试驾车型编号();
                    Lsh车型Model lsh车型Model = lsh车型Repository.findby车型编号(carId);
                    if (lsh车型Model != null)
                        carDetails = carDetails + lsh车型Model.get车型详细();

                    startTime = startTime + model试驾记录.get试驾开始时间();
                    endTime = endTime + model试驾记录.get试驾结束时间();
                    totalTime += model试驾记录.get试驾时长() == null ? "" : String.valueOf(model试驾记录.get试驾时长());
                }

                m.put("试驾车型编号", carDetails);
                m.put("试驾开始时间", startTime);
                m.put("试驾结束时间", endTime);
                m.put("试驾时长", totalTime);
            }
        }
        return list;
    }

    @Override
    public int saveItaskData(List<Itask基础设置Model> itaskDataModel) {
        int success = 0;
        for (Itask基础设置Model itaskModel : itaskDataModel) {
            try {
                itaskRepository.save(itaskModel);
                success++;
            } catch (Exception e) {
                logger.error("运行异常。", e);
            }
        }
        return success;
    }

    @Override
    public List filterCarType(String permit, String userName) {
        List<String> brands = brandService.getBrandListByUser(userName);

        return setRepository.filterCarType(brands);
    }

    @Override
    public String saveBatchSnpSettingData(String permit, List<SNPSettingRequest> snpDataList) {
        //return setRepository.saveBatchSnpSettingData(snpDataList);

        String result = null;
        try {
            if (snpDataList != null && !snpDataList.isEmpty()) {
                boolean flag = false;
                snpSettingRepository.deleteSnpDataByPermit(permit, "190001", snpDataList.get(0).ym);
                for (SNPSettingRequest snpSettingRequest : snpDataList) {
                    flag = false;
                    //校验 许可 是否和登录许可匹配，不匹配则不处理
                    if (!permit.equals(snpSettingRequest.permit)) {
                        result = snpSettingRequest.permit + "许可不匹配;";
                        break;
                    }
                    //校验 年月 是否为空，为空则不处理
                    if (Strings.isNullOrEmpty(snpSettingRequest.ym)) {
                        result = snpSettingRequest.ym + "年月为空;";
                        break;
                    }
                    //校验 车型详细 是否为空，为空则不处理
                    if (Strings.isNullOrEmpty(snpSettingRequest.carDetail)) {
                        result = snpSettingRequest.carDetail + "车款为空;";
                        break;
                    }

                    int carCode = 0;
                    int apperanceCode = 0;
                    //校验 车型外观 是否为空， 为空则默认为 0;
//                    if (Strings.isNullOrEmpty(snpSettingRequest.carColor)) {
                        //无颜色
                        //查询车型编号
                        List<Integer> carCodeList = lsh车型Repository.queryCarCodeByCarDetail(snpSettingRequest.carDetail);
                        if (carCodeList == null || carCodeList.isEmpty()) {
                            result = snpSettingRequest.carDetail + "车款不匹配;";
                            break;
                        }
                        carCode = carCodeList.get(0);
//                    } else {
//                        //有颜色的情况：
//                        //查询车型编号,车型外观编号
//                        List carCodeList = setRepository.getCarCodeAndCarColorCode(snpSettingRequest.carDetail, snpSettingRequest.carColor);
//                        if (carCodeList == null || carCodeList.isEmpty()) {
//                            result = "车款" + snpSettingRequest.carDetail + "和颜色" + snpSettingRequest.carColor + "不正确;";
//                        }
//                        Map carCodeMap = (Map) carCodeList.get(0);
//                        if (carCodeMap.get("carCode") == null || carCodeMap.get("apperanceCode") == null) {
//                            result = "车款" + snpSettingRequest.carDetail + "和颜色" + snpSettingRequest.carColor + "不正确;";
//                        }
//                        carCode = Integer.parseInt(carCodeMap.get("carCode").toString());
//                        apperanceCode = Integer.parseInt(carCodeMap.get("apperanceCode").toString());
//                    }

                    SnpSettingModel snpSettingModelSI = new SnpSettingModel();
                    snpSettingModelSI.setPermit(permit);
                    snpSettingModelSI.setyM("190001");
                    snpSettingModelSI.setCarCode(carCode);
                    snpSettingModelSI.setApperanceCode(apperanceCode);
                    snpSettingModelSI.setBiStandardConfigMsrpTaxIncluded(snpSettingRequest.getBiStandardConfMSRPTaxIncluded());
                    snpSettingModelSI.setCashDiscountAndSiCostCelling(snpSettingRequest.getCashDiscountAndSICostCelling());
                    snpSettingModelSI.setSiCost(snpSettingRequest.getSiCost());
                    snpSettingModelSI.setStandardConfigurationAreaPriceLimitSnpTaxIncluded(snpSettingRequest.getStandardConfigAreaPriceLimitSNPTaxIncluded());
                    snpSettingModelSI.setBmbsRetailSi(snpSettingRequest.getBmbsRetailSI());
                    snpSettingModelSI.setBmbsWholesaleSi(snpSettingRequest.getBmbsWholeSaleSI());
                    snpSettingRepository.save(snpSettingModelSI);

                    //更新ta--bmbsTA或lshTA大于0才更新,如果bmbsTA和lshTA都要改为0，就只能从界面上修改了
                    /*if ((snpSettingRequest.bmbsTA != null && !"".equals(snpSettingRequest.bmbsTA) && Integer.parseInt(snpSettingRequest.bmbsTA) > 0)
                            || (snpSettingRequest.lshTA != null && !"".equals(snpSettingRequest.lshTA) && Integer.parseInt(snpSettingRequest.lshTA) > 0)) {*/
                    SnpSettingModel snpSettingModelTA = new SnpSettingModel();
                    snpSettingModelTA.setPermit(permit);
                    snpSettingModelTA.setyM(snpSettingRequest.ym);
                    snpSettingModelTA.setCarCode(carCode);
                    snpSettingModelTA.setApperanceCode(apperanceCode);
                    snpSettingModelTA.setBmbsTa(snpSettingRequest.getBmbsTA());
                    snpSettingModelTA.setLshTa(snpSettingRequest.getLshTA());
                    snpSettingRepository.save(snpSettingModelTA);
                    /*} else {
                        result = "bmbsTA或lshTA必须大于0,如果bmbsTA和lshTA都要改为0，就只能从界面上修改了";
                        break;
                    }*/
                    flag = true;
                }

                // 校验表格中数据是否唯一 （规则：根据车款+颜色作为唯一条件判断，如果车款+颜色，唯一，表示只有一条数据。颜色如果为空，只以车款为唯一判断）
                List<String> keys = new ArrayList<String>();
                for (SNPSettingRequest snpSettingRequest : snpDataList) {
                    String carDetail = snpSettingRequest.carDetail == null ? "" : snpSettingRequest.carDetail.trim();  // 车款
                    String carColor = snpSettingRequest.carColor == null ? "" : snpSettingRequest.carColor.trim();   //  颜色
                    keys.add(carDetail + carColor);  // 车款+颜色的组合为唯一键
                }
                HashSet<String> set = new HashSet<String>(keys);
                if (keys.size() != set.size()) {
                    flag = false;
                    result = "存在重复的数据，车款和颜色的组合必须唯一，请修改后重新导入!";
                }

                if (!flag) {
                    TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
                } else {
                    result = "success";
                }
            } else {
                result = "未传入SNP数据";
            }
        } catch (Exception e) {
            logger.error("snp导入数据异常", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    @Override
    public PageData getSNPDataByYM(GetSNPSettingReq snpSettingReq) {
        return setRepository.getSNPDataByYM(snpSettingReq);
    }

    @Override
    public PageData getUnSaleUserReq(unSaleUserRequest unSaleUserReq) {
        return setRepository.getUnSaleUserInfo(unSaleUserReq);
    }

    @Override
    public int getUnSaleUserNum(unSaleUserRequest unSaleUserReq) {
        return setRepository.getUnSaleUserNum(unSaleUserReq);
    }

    @Override
    public boolean deleteUser(String username) {
        try {
            userRepository.deleteUserByName(username);
        } catch (Exception e) {
            logger.error("运行异常。", e);
            return false;
        }
        return true;
    }

    @Override
    public ResultData saveUser(用户Model userData, String state) {
        try {
            用户Model oldUserModel = userRepository.findOne(userData.get用户名());
            // state = 1,新增用户； state = 2， 修改用户
            if (oldUserModel != null) {
                if ("1".equals(state)) {
                    logger.info(userData.get用户名() + "--用户名已存在，不能新增");
                    return new ResultData("false","该用户已存在");
                }
                oldUserModel.set许可(userData.get许可());
                oldUserModel.set人员姓名(userData.get人员姓名());
                oldUserModel.set人员电话(userData.get人员电话());
                oldUserModel.set所属部门(userData.get所属部门());
                oldUserModel.set角色(StringUtils.isNullOrBlank(userData.get角色())?userData.get角色():userData.get角色().replace(",",";"));
                oldUserModel.set品牌(userData.get品牌());
                oldUserModel.set更新日期(userData.get更新日期());
                oldUserModel.set密码(userData.get密码());
                oldUserModel.setKpi使用状态(userData.getKpi使用状态());
                oldUserModel.set接待状态(userData.get接待状态());
                oldUserModel.set电子邮箱(userData.get电子邮箱());
                oldUserModel.set分组编号(userData.get分组编号());
                oldUserModel.set删除状态(userData.get删除状态());
                String superior = userData.getSuperior();


                String checkedSuperior = UserUtils.superiorCheck(superior);
                if (checkedSuperior == null) {
                 return    new ResultData("false","找不到输入的所属上级，请检查");
                } else {
                    oldUserModel.setSuperior(checkedSuperior);
                }
                userRepository.save(oldUserModel);
            } else {
                if ("2".equals(state)) {
                    logger.info(userData.get用户名() + "--用户名不存在，不能修改");
                    return new ResultData("false","该用户不存在");
                }
                String superior = userData.getSuperior();
                String checkedSuperior = UserUtils.superiorCheck(superior);
                if (checkedSuperior == null) {
                    return    new ResultData("false","找不到输入的所属上级账号，请检查");
                }
                String blank = userData.get用户名();
                //如果有空格的话、则把空格给去掉
                boolean bool = blank.contains(" ");
                if (bool){
                    String user = blank.replace(" ","");
                    userData.set用户名(user);
                    logger.info("您输入的用户名有空格,blank{},示例：user{}",blank,user);
                }
                userRepository.save(userData);
            }
            return    new ResultData("true","保存成功");
        } catch (Exception e) {
            logger.error("保存用户数据异常。", e);
            return new ResultData("false","系统异常");
        }
    }

    @Override
    public boolean findUserByName(String username) {
        try {
            用户Model user = userRepository.findByCode(username);
            if (user == null) {
                return false;
            }
        } catch (Exception e) {
            logger.error("运行异常。", e);
            return false;
        }
        return true;
    }

    @Override
    public List getSaleGroupName(String permit) {
        return setRepository.getSaleGroupName(permit);
    }

    @Override
    public PageData getWorkFlow(workFlowRequest workFlowReq) {
        return setRepository.getWorkFlow(workFlowReq);
    }

    @Override
    public int saveWorkFlowInfo(List<PushApprovalWorkFlowModel> workFlowModelList) {
        int success = 0;
        for (PushApprovalWorkFlowModel workFlowModel : workFlowModelList) {
            try {
                pushWorkFlowRepository.save(workFlowModel);
                success++;
            } catch (Exception e) {
                logger.error("运行异常。", e);
            }
        }
        return success;
    }

    @Override
    public PageData getLshCarProInfo(@RequestBody permitRequest permitReq) {
        return setRepository.getLshCarProInfo(permitReq);
    }

    @Override
    @Transactional
    public int saveCarProInfo(List<Lsh随车项目设置Model> carProModelList) throws IOException, ClassNotFoundException, ParseException {
        Timestamp ts = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date());
        Calendar c = Calendar.getInstance();
        int success = 0;
        for (int i = 0; i < carProModelList.size(); i++) {
            Lsh随车项目设置Model s = carProModelList.get(i);
            s.set创建时间(ts);
            s.set更新时间(ts);
            List<Lsh随车项目设置Model> oldlist1 = lshCarProRepository.lsh随车findBy车型编号And许可(s.get车型编号(), s.get许可());
            if (oldlist1.size() > 0) {
                for (int m = 0; m < oldlist1.size(); ) {
                    Lsh随车项目设置Model old = oldlist1.get(m);

                    Date oldS = new Date(old.get启用时间().getTime());
                    Date oldE = new Date(old.get停用时间().getTime());
                    Date oldStartTime = DateFormatUtils.getFormatDate("yyyy-MM-dd", oldS);
                    Date oldEndTime = DateFormatUtils.getFormatDate("yyyy-MM-dd", oldE);

                    Date st = new Date(s.get启用时间().getTime());
                    Date et = new Date(s.get停用时间().getTime());
                    Date startTime = DateFormatUtils.getFormatDate("yyyy-MM-dd", st);
                    Date endTime = DateFormatUtils.getFormatDate("yyyy-MM-dd", et);
                    //如果旧数据的开始结束时间在参数之间之内,删除记录
                    Date dtt = new SimpleDateFormat("yyyy-MM-dd").parse("2030-12-31");
                    if (dtt.getTime() == endTime.getTime()) {
                        if (oldStartTime.getTime() >= startTime.getTime()) {
                            lshCarProRepository.delete(old);
                            oldlist1.remove(old);
                        } else {
                            m++;
                        }
                    } else {
                        if ((oldStartTime.getTime() >= startTime.getTime() && oldStartTime.getTime() <= endTime.getTime()) &&
                                (oldEndTime.getTime() >= startTime.getTime() && oldEndTime.getTime() <= endTime.getTime())) {
                            lshCarProRepository.delete(old);
                            oldlist1.remove(old);
                        } else {
                            m++;
                        }
                    }

                }
                List<Lsh随车项目设置Model> oldlist = lshCarProRepository.lsh随车findBy车型编号And许可(s.get车型编号(), s.get许可());
                if (oldlist.size() == 0) {
                    lshCarProRepository.save(s);
                    success++;
                    continue;
                }
                for (int j = 0; j < oldlist.size(); j++) {
                    Lsh随车项目设置Model old = oldlist.get(j);

                    Date oldS = new Date(old.get启用时间().getTime());
                    Date oldE = new Date(old.get停用时间().getTime());
                    Date oldStartTime = DateFormatUtils.getFormatDate("yyyy-MM-dd", oldS);
                    Date oldEndTime = DateFormatUtils.getFormatDate("yyyy-MM-dd", oldE);

                    Date st = new Date(s.get启用时间().getTime());
                    Date et = new Date(s.get停用时间().getTime());
                    Date startTime = DateFormatUtils.getFormatDate("yyyy-MM-dd", st);
                    Date endTime = DateFormatUtils.getFormatDate("yyyy-MM-dd", et);

                    //如果旧数据的开始结束时间在参数之间之内,删除记录
                    if ((oldStartTime.getTime() >= startTime.getTime() && oldStartTime.getTime() <= endTime.getTime()) &&
                            (oldEndTime.getTime() >= startTime.getTime() && oldEndTime.getTime() <= endTime.getTime())) {
                        lshCarProRepository.delete(old.get项目成本编号());
                        lshCarProRepository.save(s);
                        success++;
                        break;
                    } else if (startTime.getTime() < oldStartTime.getTime() && endTime.getTime() < oldStartTime.getTime()) {
                        //如果参数的开始时间和结束时间都在旧数据的开始时间之前，新增
                        lshCarProRepository.save(s);
                        success++;
                        break;
                    } else if (startTime.getTime() < oldStartTime.getTime() && endTime.getTime() >= oldStartTime.getTime() &&
                            endTime.getTime() <= oldEndTime.getTime()) {
                        //如果参数的开始时间大于旧数据的开始时间，参数的结束时间在旧数据日期之间
                        //将旧数据的开始时间更改为参数结束日期的后一天
                        c.setTime(oldStartTime);
                        int day = c.get(Calendar.DATE);
                        c.set(Calendar.DATE, day + 1);
                        Date modifyOldStartTime = DateFormatUtils.getFormatDate("yyyy-MM-dd", c.getTime());
                        java.sql.Date modifyOldStartTime1 = new java.sql.Date(modifyOldStartTime.getTime());
                        java.sql.Date sqlDate = java.sql.Date.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(modifyOldStartTime1));
                        lshCarProRepository.updateById(old.get项目成本编号(), sqlDate);
                        lshCarProRepository.save(s);
                        success++;
                        break;
                    } else if (startTime.getTime() >= oldStartTime.getTime() && endTime.getTime() <= oldEndTime.getTime()) {
                        //如果参数的开始时间和结束时间均在旧数据时间之内
                        Lsh随车项目设置Model cloned随车 = (Lsh随车项目设置Model) CloneUtils.deepClone(old);
                        c.setTime(startTime);
                        int day = c.get(Calendar.DATE);
                        c.set(Calendar.DATE, day - 1);
                        Date modifyOldStartTime = DateFormatUtils.getFormatDate("yyyy-MM-dd", c.getTime());
                        java.sql.Date modifyOldStartTime1 = new java.sql.Date(modifyOldStartTime.getTime());
                        java.sql.Date sqlDate = java.sql.Date.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(modifyOldStartTime1));

                        c.setTime(endTime);
                        int day2 = c.get(Calendar.DATE);
                        c.set(Calendar.DATE, day2 + 1);
                        Date modifyOldStartTime2 = DateFormatUtils.getFormatDate("yyyy-MM-dd", c.getTime());
                        java.sql.Date modifyOldStartTime3 = new java.sql.Date(modifyOldStartTime2.getTime());
                        java.sql.Date sqlDate2 = java.sql.Date.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(modifyOldStartTime3));
                        old.set停用时间(sqlDate);
                        cloned随车.set启用时间(sqlDate2);
                        lshCarProRepository.save(old);
                        cloned随车.set项目成本编号(null);
                        lshCarProRepository.save(cloned随车);
                        lshCarProRepository.save(s);
                        success++;
                        break;
                    } else if ((startTime.getTime() >= oldStartTime.getTime() && startTime.getTime() <= oldEndTime.getTime()) && endTime.getTime() > oldEndTime.getTime()) {
                        //如果参数的开始时间在旧数据之间，结束时间在旧数据之外，分两种情况：结束时间在第一条旧数据的外，但不在
                        //第二记录内，或在第二条数据内
                        //先判断有没有第二条旧数据
                        if ((j + 2) <= oldlist.size()) {
                            Lsh随车项目设置Model old2 = oldlist.get(j + 1);
                            Date oldS2 = new Date(old2.get启用时间().getTime());
                            Date oldE2 = new Date(old2.get停用时间().getTime());
                            Date oldStartTime2 = DateFormatUtils.getFormatDate("yyyy-MM-dd", oldS2);
                            Date oldEndTime2 = DateFormatUtils.getFormatDate("yyyy-MM-dd", oldE2);
                            if (endTime.getTime() < oldStartTime2.getTime()) {
                                //如果参数的结束日期在第二条旧数据之前,修改旧数据第一条的结束时间为参数开始时间前一天
                                c.setTime(startTime);
                                int day = c.get(Calendar.DATE);
                                c.set(Calendar.DATE, day - 1);
                                Date modifyOldStartTime = DateFormatUtils.getFormatDate("yyyy-MM-dd", c.getTime());
                                java.sql.Date modifyOldStartTime1 = new java.sql.Date(modifyOldStartTime.getTime());
                                java.sql.Date sqlDate = java.sql.Date.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(modifyOldStartTime1));
                                old.set停用时间(sqlDate);
                                lshCarProRepository.save(old);
                                lshCarProRepository.save(s);
                                success++;
                                break;
                            }
                            if (endTime.getTime() >= oldStartTime2.getTime() && endTime.getTime() <= oldEndTime2.getTime()) {
                                //如果参数的结束日期在第二条旧数据之间
                                c.setTime(startTime);
                                int day = c.get(Calendar.DATE);
                                c.set(Calendar.DATE, day - 1);
                                Date modifyOldStartTime = DateFormatUtils.getFormatDate("yyyy-MM-dd", c.getTime());
                                java.sql.Date modifyOldStartTime1 = new java.sql.Date(modifyOldStartTime.getTime());
                                java.sql.Date sqlDate = java.sql.Date.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(modifyOldStartTime1));

                                c.setTime(endTime);
                                int day2 = c.get(Calendar.DATE);
                                c.set(Calendar.DATE, day2 + 1);
                                Date modifyOldStartTime2 = DateFormatUtils.getFormatDate("yyyy-MM-dd", c.getTime());
                                java.sql.Date modifyOldStartTime3 = new java.sql.Date(modifyOldStartTime2.getTime());
                                java.sql.Date sqlDate2 = java.sql.Date.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(modifyOldStartTime3));

                                old.set停用时间(sqlDate);
                                old2.set启用时间(sqlDate2);
                                lshCarProRepository.save(old);
                                lshCarProRepository.save(old2);
                                lshCarProRepository.save(s);
                                success++;
                                break;
                            }
                        } else {
                            //如果没有第二条旧数据
                            c.setTime(startTime);
                            int day = c.get(Calendar.DATE);
                            c.set(Calendar.DATE, day - 1);
                            Date modifyOldStartTime = DateFormatUtils.getFormatDate("yyyy-MM-dd", c.getTime());
                            java.sql.Date modifyOldStartTime1 = new java.sql.Date(modifyOldStartTime.getTime());
                            java.sql.Date sqlDate = java.sql.Date.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(modifyOldStartTime1));
                            old.set停用时间(sqlDate);
                            lshCarProRepository.save(old);
                            lshCarProRepository.save(s);
                            success++;
                            break;
                        }
                    } else if (startTime.getTime() > oldEndTime.getTime()) {
                        //如果参数的开始时间大于旧数据的结束时间
                        //判断有没有下一记录
                        if ((j + 2) <= oldlist.size()) {
                            Lsh随车项目设置Model old2 = oldlist.get(j + 1);
                            Date oldS2 = new Date(old2.get启用时间().getTime());
                            Date oldE2 = new Date(old2.get停用时间().getTime());
                            Date oldStartTime2 = DateFormatUtils.getFormatDate("yyyy-MM-dd", oldS2);
                            Date oldEndTime2 = DateFormatUtils.getFormatDate("yyyy-MM-dd", oldE2);
                            if (endTime.getTime() < oldStartTime2.getTime()) {
                                //如果参数的结束时间在第二条开始时间之前
                                lshCarProRepository.save(s);
                                success++;
                                break;
                            }
                            if (endTime.getTime() > oldStartTime2.getTime() && endTime.getTime() <= oldEndTime2.getTime()) {
                                c.setTime(endTime);
                                int day2 = c.get(Calendar.DATE);
                                c.set(Calendar.DATE, day2 + 1);
                                Date modifyOldStartTime2 = DateFormatUtils.getFormatDate("yyyy-MM-dd", c.getTime());
                                java.sql.Date modifyOldStartTime3 = new java.sql.Date(modifyOldStartTime2.getTime());
                                java.sql.Date sqlDate2 = java.sql.Date.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(modifyOldStartTime3));
                                old2.set启用时间(sqlDate2);
                                lshCarProRepository.save(s);
                                lshCarProRepository.save(old2);
                                success++;
                                break;
                            }

                        } else {
                            //没有下一条记录
                            lshCarProRepository.save(s);
                            success++;
                            break;
                        }
                    }
                }
            } else {
                lshCarProRepository.save(s);
                success++;
            }
        }
        return success;
    }

    @Override
    public PageData getInOutAccount(inOutAccountRequest accRequset, String permit) {
        logger.info("getInOutAccount传入参数为:" + JsonObjectUtils.writeAsJson(accRequset));
        return setRepository.getInOutAccount(accRequset, permit);
    }

    /**
     * 最后更改：16/11/7
     */
    @Override
    @Transactional
    public ResultData updateCallInDetail(updateCallInDetail callInModel, String liveusername) {
        logger.info("updateCallInDetail传入参数为:" + JsonObjectUtils.writeAsJson(callInModel));
        String errMsg = "调车付款异常";
        try {
            BigDecimal actualPaymentAmount = callInModel.调车款项实付金额;
            Date actualPaymentDate = callInModel.调车款项实付日期;
            java.sql.Date sqldate = new java.sql.Date(DateFormatUtils.getFormatDate("yyyy-MM-dd", actualPaymentDate).getTime());//sqldate格式的acr_date
            String vin = callInModel.vin;
            Timestamp nowdate = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date());
            java.sql.Date nowdate1 = new java.sql.Date(new Date().getTime());
            //获取车架号为VIN的库存
            Lsh库存表Model stockMo = lsh库存表Repository.findLshRecordByVin(vin);
            if (!"调车发票完毕".equals(stockMo.get调车财务状态())) { // 如果处于非待付款状态
                errMsg = "此车已经付款";
                throw new Exception();
            }
            Integer stockCodel = stockMo.get库存编号();
            lsh库存表Repository.updateCallInDetail(stockCodel, "调车付款完成");
            //修改car_transfer_log 表中库存编号为stockCodel行的：actual_payment_amount (实际付款金额),actual_payment_date ,a.modify_date ，modify_user
            CarTransferLogModel carTransferLogModel = carTransferLogRepository.findById(callInModel.id);
            carTransferLogModel.setActualPaymentAmount(actualPaymentAmount);
            carTransferLogModel.setActualPaymentDate(sqldate);
            carTransferLogModel.setFinancialStatus("调车付款完成");
            carTransferLogModel.setFundOutDate(nowdate1);
            carTransferLogModel.setFundOutUser(liveusername);
            carTransferLogModel.setModifyUser(liveusername);
            carTransferLogModel.setModifyDate(nowdate);
            carTransferLogRepository.save(carTransferLogModel);
            return new ResultData("true", null, null);
        } catch (Exception e) {
            logger.error(errMsg, e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            return new ResultData("false", errMsg, null);
        }
        /*try {
            if (!Strings.isNullOrEmpty(callInModel.get许可())
                    && !Strings.isNullOrEmpty(callInModel.getVin())) {
                callInRepository.save(callInModel);
            } else {
                LogFactory.getLog(SetServiceImpl.class).info("VIN,PERMIT均不能为空!");
                return false;
            }
        } catch (Exception e) {
            LogFactory.getLog(SetServiceImpl.class).info(e.getStackTrace());
            return false;
        }
        return true;*/
    }

    /**
     * 最后更改：16/11/7
     */
    @Override
    @Transactional
    public ResultData updateCallOutDetail(updateCallOutDetail callOutModel, String liveusername) {
        logger.info("updateCallOutDetail传入参数为:" + JsonObjectUtils.writeAsJson(callOutModel));
        String errMsg = "调车收款确认异常";
        try {
            CarTransferLogModel transMo = carTransferLogRepository.findById(callOutModel.id);
            Date fundOutDt = transMo.getFundOutDate();
            Date fundInDt = callOutModel.调车款项实收日期;
            if (fundInDt.before(fundOutDt)) { // 收款日期应该等于晚于付款日期
                return new ResultData("false", "收款日期不能早于付款日期", null);
            }
            java.sql.Date actualAcceptDate = new java.sql.Date(DateFormatUtils.getFormatDate("yyyy-MM-dd", fundInDt).getTime());
            String vin = callOutModel.vin;
            Timestamp nowdate = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date());
            //根据VIN获得  库存编号
            Lsh库存表Model stockMo = lsh库存表Repository.findLshRecordByVin(vin);//获取车架号为VIN的库存
            if (!"调车付款完成".equals(stockMo.get调车财务状态())) { // 非待收款状态时
                errMsg = "此车收款已经完成";
                throw new Exception();
            }
            //修改库存表的 调车款到账金额，调车款到账日期，调车款财务状态
            stockMo.set调车款项到帐金额(callOutModel.调车款项实收金额);
            stockMo.set调车款项到帐日期(actualAcceptDate);
            stockMo.set调车财务状态("调车款项到账");
            lsh库存表Repository.save(stockMo);
            //修改 car_transfer_log表中的 modify_user   modify_date
            java.sql.Date nowdate1 = new java.sql.Date(nowdate.getTime());
            transMo.setModifyDate(nowdate);
            transMo.setMoneyTransferdAmount(callOutModel.调车款项实收金额);
            transMo.setMoneyTransferdDate(actualAcceptDate);
            transMo.setFinancialStatus("调车款项到账");
            transMo.setFundInUser(liveusername);
            transMo.setFundInDate(nowdate1);
            carTransferLogRepository.save(transMo);
            return new ResultData("true", null, null);
        } catch (Exception e) {
            logger.error(errMsg, e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            return new ResultData("false", errMsg, null);
        }

      /*  try {
            if (!Strings.isNullOrEmpty(callOutModel.get许可())
                    && !Strings.isNullOrEmpty(callOutModel.getVin())) {
                callOutRepository.save(callOutModel);
            } else {
                LogFactory.getLog(SetServiceImpl.class).info("VIN,PERMIT均不能为空!");
                return false;
            }
        } catch (Exception e) {
            LogFactory.getLog(SetServiceImpl.class).info(e.getStackTrace());
            return false;
        }
        return true;*/
    }

    @Override
    public List getCarColorAndAppearance() {
        return setRepository.getCarColorAndAppearance();
    }

    @Override
    public List getMaxEntryNumber() {
        return setRepository.getMaxEntryNumber();
    }

    @Override
    public boolean saveDealerAttachmentPloicy(DealerAttachmentPolicyModel model) {
        Assert.notNull(model);
        boolean flag;
        try {
            dApilicyRepository.save(model);
            flag = true;
        } catch (Exception e) {
            flag = false;
            logger.error("数据保存异常。", e);
        }
        return flag;
    }

    @Override
    public boolean updDealerAttachmentPolicyStatu(String status, Integer id, String permit) {
        boolean flag;
        try {
            Integer itimcount= dApilicyRepository.selectDealerAttachmentById(id);

            dApilicyRepository.updDealerAttachmentPolicyStatu(status, itimcount, permit);
            flag = true;
        } catch (Exception e) {
            flag = false;
            logger.error("数据更新异常。", e.getMessage());
        }
        return flag;
    }

    @Override
    public PageData getDealerAttachmentPolicy(GetDAttachmentPolicyListRequest request) {
        request = MoreObjects.firstNonNull(request, new GetDAttachmentPolicyListRequest());
        return setRepository.getDealerAttachmentPolicy(request.getPageSize(), request.getPageIndex(), request.permit, request.department, request.item, request.车型, request.ncType);
    }

    @Override
    public List getDistributorInfo(String permitBMBS) {
        return setRepository.getDistributorInfo(permitBMBS);
    }

    @Override
    public boolean updDealerAttachmentPolicyStatu(Lsh市场设置Model model) {
        boolean flag;
        try {
            Lsh市场设置Model one = lshMarketSetRepository.findOne(model.get市场编号());
            if (null != model.get创建时间() && !"".equals(model.get创建时间())) {
                one.set创建时间(model.get创建时间());
            }
            if (null != model.get启用状态() && !"".equals(model.get启用状态())) {
                one.set启用状态(model.get启用状态());
            }
            if (null != model.get更新时间() && !"".equals(model.get更新时间())) {
                one.set更新时间(model.get更新时间());
            }
            if (null != model.get更新账号() && !"".equals(model.get更新账号())) {
                one.set更新账号(model.get更新账号());
            }
            if (null != model.get来源() && !"".equals(model.get来源())) {
                one.set来源(model.get来源());
            }
            if (null != model.get来源分类() && !"".equals(model.get来源分类())) {
                one.set来源分类(model.get来源分类());
            }
            if (null != model.get渠道() && !"".equals(model.get渠道())) {
                one.set渠道(model.get渠道());
            }
            if (null != model.get许可() && !"".equals(model.get许可())) {
                one.set许可(model.get许可());
            }
            lshMarketSetRepository.save(one);
            flag = true;
        } catch (Exception e) {
            flag = false;
            logger.error("数据更新异常。", e);
        }
        return flag;
    }

    @Override
    public boolean saveDealerAttachmentPolicyStatu(Lsh市场设置Model model) {
        boolean flag;
        try {
            Lsh市场设置Model lsh市场设置Model = lshMarketSetRepository.getLsh市场设置Model(model.get渠道(), model.get来源分类(), model.get来源(), model.get许可());
            if (null != lsh市场设置Model) {
                return false;
            }
            lshMarketSetRepository.save(model);
            flag = true;
        } catch (Exception e) {
            flag = false;
            logger.error("数据保存异常。", e);
        }
        return flag;
    }

    @Override
    public PageData getLSHMarketSetting(GetLSHMarketSettingListRequest request) {
        request = MoreObjects.firstNonNull(request, new GetLSHMarketSettingListRequest());
        return setRepository.getLSHMarketSetting(request.getPageSize(), request.getPageIndex(), request.channel, request.permit, request.sourceType);
    }

    @Override
    public List getUserPassword(UserInfoRequest request) {
        return setRepository.getUserPassword(request.userName);
    }

    @Override
    public boolean updUserPassword(UserInfoRequest request) {
        boolean flag;
        try {
            userRepository.updUserPassword(request.userName, request.password);
            flag = true;
        } catch (Exception e) {
            flag = false;
            logger.error("数据更新异常。", e);
        }
        return flag;
    }

    @Override
    public List getUpdAcountAndTime(String permit,Integer siType) {
        return setRepository.getUpdAcountAndTime(permit,siType);
    }

    @Override
    public boolean delIncomeAdjustmentById(Integer id,Integer siType) {
        boolean flag;
        try {
            IncomeAdjustmentModel org = inAdjustmentRepository.findOne(id);
            inAdjustmentRepository.save(deleteBySiType(siType,org));
            //bmbs随车删除子项
            if(DefaultValueConstant.REPORT_LIVE_SI_BMBS == siType ){
                //级联删除子项
                if(null != org.getpNum() && !"1".equals(org.getType())){
                    sibmbsSettingRepository.delete(org.getpNum(),org.getPermit());
                }else if(null != org.getpNum() && "1".equals(org.getType())){
                    sibmbsSettingRepository.deleteStock(org.getpNum(),org.getPermit(),org.getStockCode());
                }
            }
            flag = true;
        } catch (Exception e) {
            flag = false;
            logger.error("数据删除异常。", e);
        }
        return flag;
    }

    @Override
    public List getIncomeAdjustmentInfoByFrameNum(GetIncomeAdjustmentInfoByFrameNumRequest request, Integer siType ) {
        return setRepository.getIncomeAdjustmentInfoByFrameNum(request.permit, request.frameNum,siType);
    }

    @Override
    public boolean saveIncomeAdjustmentInfo(List<IncomeAdjustmentModel> list,Integer siType,String userName,String permit) {
        boolean flag;
        try {
            for (Iterator iterator = list.iterator(); iterator.hasNext(); ) {
                IncomeAdjustmentModel model = (IncomeAdjustmentModel) iterator.next();
                Assert.notNull(model);
                model = buildOtherNonVehicle(model,siType,permit,userName);
                //检测库存ID是否存在DB用以切换持久化方式
                Date validStart = DateFormatUtils.getDateByMonthFirstDay(DateFormatUtils.getFormatDate(DateFormatUtils.getFormatDateToString(model.getAdjustDate(),DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD),DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD));
                Date validEnd = DateFormatUtils.getDateByMonthLastDay(DateFormatUtils.getFormatDate(DateFormatUtils.getFormatDateToString(model.getAdjustDate(),DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD),DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD));
                //车辆与非车辆的定位是否存在
                IncomeAdjustmentModel income  =null;
                if(!"1".equals(model.getType())){
                    //后市场特殊处理
                    if(DefaultValueConstant.REPORT_LIVE_SI_MARKET_GIVE == siType || DefaultValueConstant.REPORT_LIVE_SI_MARKET_BUY  == siType ){
                        income  = inAdjustmentRepository.getIncomeAdjustmentByValidDateMarket(permit,validStart,validEnd,model.getCarCode(),model.getType(),model.getGive());
                    }else{
                        income  = inAdjustmentRepository.getIncomeAdjustmentByValidDate(permit,validStart,validEnd,model.getCarCode(),model.getType());
                    }
                }else{
                    income  = inAdjustmentRepository.getIncomeAdjustmentByStockCode(model.getStockCode(),permit);
                }
                model.setValidStartDate(DateFormatUtils.parseStrToSqlDate(validStart));
                model.setValidEndDate(DateFormatUtils.parseStrToSqlDate(validEnd));
                if (null == income){
                    inAdjustmentRepository.save(model);
                }else{
                    inAdjustmentRepository.save(buildUpdateSiModel(model,income,siType));
                }
            }
            flag = true;
        } catch (Exception e) {
            flag = false;
            logger.error("数据保存异常。", e);
        }
        return flag;
    }

    @Override
    public PageData getIncomeAdjustmentByCondition(GetIncomeAdjustmentByConditionRequest request,Integer siType) {
        return setRepository.getIncomeAdjustmentByCondition(request.permit, request.shengchanId, request.customerName,
                request.openTicketDate, request.jibie, request.carModel, request.carVINCode, request.type,
                request.getPageSize(), request.getPageIndex(),siType);
    }

    @Override
    public PageData getNewCarSaleDetailInfo(String code,String quoteId) {
        报价单表Model 报价单表model = 报价单表Repository.getListByInitQuoteNumbers(code).get(0);
        String quotedPrice = 报价单表model.get报价编号().toString();
        return setRepository.getNewCarSaleDetailInfo(quoteId);
    }

    @Override
    public boolean updNewCarSaleInfo(销售收款详单Model model) {
        boolean flag;
        try {
            saleReceiptRepository.save(model);
            flag = true;
        } catch (Exception e) {
            flag = false;
            logger.error("数据更新异常。", e);
        }
        return flag;
    }

    @Override
    public boolean updNewCarStatu(UpdNewCarStatuRequest request) {
        boolean flag;
        try {
            financialDetailsRepository.updNewCarStatu(request.payGoal, request.recentUpdTime, request.lasUpdAccount, request.vin);
            flag = true;
        } catch (Exception e) {
            flag = false;
            logger.error("数据更新异常。", e);
        }
        return flag;
    }


    @Override
    public List getSaleItemsSetting(String permit, String setItems) {
        return setRepository.getSaleItemsSetting(permit, setItems);
    }

    @Override
    public boolean saveSaleItemsSetting(List<销售项目设置Model> list) {
        boolean flag;
        try {
            for (Iterator iterator = list.iterator(); iterator.hasNext(); ) {
                销售项目设置Model 销售项目设置Model = (销售项目设置Model) iterator.next();
                saleItemRepository.save(销售项目设置Model);
            }
            flag = true;
        } catch (Exception e) {
            flag = false;
            logger.error("数据保存异常。", e);
        }
        return flag;
    }

    /**
     * 老财务的保留接口
     * @param onCredit
     * @param realPay
     * @param finance
     * @param quoteNo
     * @param account
     * @param customerName
     * @param salesInfo
     * @param carType
     * @param permit
     * @return
     */
    @Override
    @Transactional
    public ResultData updateNewCarSaleMoney(String onCredit,String realPay, String finance, int quoteNo, String account, String customerName, String salesInfo, String carType, String permit) {
        ResultData result = new ResultData("true",null,null);
        try {
            //1.8优化 pc出入账新增应收总价的计算和实收总价的录入
            BigDecimal b1=new BigDecimal(报价付款详细Repository.getTotal(quoteNo).get应付金额());
            BigDecimal b2=new BigDecimal(报价付款详细Repository.getTotalNow(quoteNo));
            BigDecimal b3= b1.setScale(2,   BigDecimal.ROUND_HALF_UP);
            BigDecimal b4= b2.setScale(2,   BigDecimal.ROUND_HALF_UP);
            String totalNow=b4.subtract(b3).toString();
            报价付款详细Repository.updateTotal(totalNow, quoteNo);//更新总计行的应付金额
            报价付款详细Repository.updateTotal2(totalNow, quoteNo);//更新总计行的实付金额

            //修改金额
            paymentDetailRepository.updateSaleMoney( finance, quoteNo, account);
            //修改新车销售状态
            报价单表Model 报价单表Model = 报价单表Repository.findBy报价编号(quoteNo);

            // 保存是否挂账
            if (!StringUtils.isNullOrBlank(onCredit)) {
                报价单表Model.setOnCredit("是".equals(onCredit) ? 1 : 0);
                报价单表Repository.save(报价单表Model);
            }

            报价交车表Model model交车=  报价交车表Repository.findby编号(报价单表Model.get交车());
                if(model交车!=null){
                    model交车.set退票时间(null);
                    model交车.set退票提交时间(null);
                    报价交车表Repository.save(model交车);
                }

            //同时修改最新的一条财务数据（2017-01-17修改）
            报价单表Model 报价单表Model2 = 报价单表Repository.findBy初始报价编号(报价单表Model.get初始报价单号()).get(0);
            paymentDetailRepository.updateSaleMoney( finance, 报价单表Model2.get报价编号(), account);

            Integer 顾客编号 = 报价单表Model.get顾客编号();
            顾客记录汇总Model 顾客记录汇总Model = 顾客记录汇总Repository.findCusByCustomerID(顾客编号);
            if (顾客记录汇总Model!=null&&顾客记录汇总Model.get新车销售状态()!=null&&顾客记录汇总Model.get新车销售状态()<15){
                顾客记录汇总Model.set新车销售状态(15);
                顾客记录汇总Repository.save(顾客记录汇总Model);
            }
            LshMsgUtils.getLshMsg(permit, account, permit, salesInfo, MessageContext.updateQuotation(customerName, carType), MessageType.Type.getName(MessageType.MSG_TYPE_FINANCE_SYS));

            // 第三方精品
            String typeName = null;  // 类型（分为“正常出入账”、“合同修改出入账”）
            TBoutiqueCallCheckModel checkModel = tBoutiqueCallCheckRepository.findBycontroactNUm(model交车.get合同号());
            if (null == checkModel ||
                    (DefaultValueConstant.CHECK_CAR_SOURCE_HOLD.equals(checkModel.getCheckStatus()) &&
                     (0 == checkModel.getOrderType() || ApprovalWorkFlowEnum.AGREEMENT_UPDATE == checkModel.getOrderType()))) {
                // 精品信息确认维护表
                if (null == checkModel) {
                    typeName = "正常出入账";
                    checkModel = new TBoutiqueCallCheckModel();
                    checkModel.setQuotaId(报价单表Model.get报价编号().toString());
                    checkModel.setContractNum(model交车.get合同号());
                    checkModel.setCheckStatus(DefaultValueConstant.CHECK_CAR_SOURCE_PASS); // 设置为已确认
                    checkModel.setScName(salesInfo);
                    checkModel.setPermit(报价单表Model.get许可());
                    checkModel.setOrderType(0);  // 正常流程
                    checkModel.setCreatedTime(DateUtils.getCurrentTimestamp());
                } else {
                    typeName = "合同修改出入账";
                    checkModel.setCheckStatus(DefaultValueConstant.CHECK_CAR_SOURCE_PASS); // 设置为已确认
                    checkModel.setUpdateTime(DateUtils.getCurrentTimestamp());
                }

                tBoutiqueCallCheckRepository.save(checkModel);

                // 调用三方精品库存系统
                StockResult stockResult = reduceThirdBoutiqueStock(0,typeName,quoteNo, salesInfo, permit, 报价单表Model, model交车, 顾客记录汇总Model);
                if ("fail".equals(stockResult.getCode())) {
                    logger.error("第三方精品库存扣减失败,流程类型:{}，code：{}，message：{}，obj：{}。permit：{},报价编号：{}",typeName,stockResult.getCode(),stockResult.getMessage(),stockResult.getObj(),permit,quoteNo);
                    TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
                    result.setResult("false");
                    result.setMessage("预约施工单生成失败");
                }
            }

        } catch (Exception e) {
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            logger.error("数据更新异常。", e);
            result.setResult("false");
            result.setMessage("保存失败");
        }
        return result;
    }

    /**
     * 新财务的接口
     * @param quoteNo
     * @param saleInfo
     * @param permit
     * @return
     */
    @Override
    @Transactional
    public ResultData updateNewCarSaleMoneyForNewFinance(int quoteNo,String saleInfo,String permit) {
        logger.info("开始调用出入账确认接口，报价编号：{}",quoteNo);
        ResultData result = new ResultData("true",null,null);
        try {
            //修改新车销售状态
            报价单表Model 报价单表Model = 报价单表Repository.findBy报价编号(quoteNo);

            报价交车表Model model交车=  报价交车表Repository.findby编号(报价单表Model.get交车());
            if(model交车!=null){
                model交车.set退票时间(null);
                model交车.set退票提交时间(null);
                报价交车表Repository.save(model交车);
            }

            Integer 顾客编号 = 报价单表Model.get顾客编号();
            顾客记录汇总Model 顾客记录汇总Model = 顾客记录汇总Repository.findCusByCustomerID(顾客编号);
            if (顾客记录汇总Model!=null&&顾客记录汇总Model.get新车销售状态()!=null&&顾客记录汇总Model.get新车销售状态()<15){
                顾客记录汇总Model.set新车销售状态(15);
                顾客记录汇总Repository.save(顾客记录汇总Model);
            }

            // 第三方精品
            String typeName = null;  // 类型（分为“正常出入账”、“合同修改出入账”）
            TBoutiqueCallCheckModel checkModel = tBoutiqueCallCheckRepository.findBycontroactNUm(model交车.get合同号());
            if (null == checkModel ||
                    (DefaultValueConstant.CHECK_CAR_SOURCE_HOLD.equals(checkModel.getCheckStatus()) &&
                            (0 == checkModel.getOrderType() || ApprovalWorkFlowEnum.AGREEMENT_UPDATE == checkModel.getOrderType()))) {
                String salesInfo = 用户Repository.findBy许可And用户名(permit,saleInfo).get人员姓名();
                // 精品信息确认维护表
                if (null == checkModel) {
                    typeName = "正常出入账";
                    checkModel = new TBoutiqueCallCheckModel();
                    checkModel.setQuotaId(报价单表Model.get报价编号().toString());
                    checkModel.setContractNum(model交车.get合同号());
                    checkModel.setCheckStatus(DefaultValueConstant.CHECK_CAR_SOURCE_PASS); // 设置为已确认
                    checkModel.setScName(salesInfo);
                    checkModel.setPermit(报价单表Model.get许可());
                    checkModel.setOrderType(0);  // 正常流程
                    checkModel.setCreatedTime(DateUtils.getCurrentTimestamp());
                } else {
                    typeName = "合同修改出入账";
                    checkModel.setCheckStatus(DefaultValueConstant.CHECK_CAR_SOURCE_PASS); // 设置为已确认
                    checkModel.setUpdateTime(DateUtils.getCurrentTimestamp());
                }
                tBoutiqueCallCheckRepository.save(checkModel);

                // 调用三方精品库存系统
                StockResult stockResult = reduceThirdBoutiqueStock(0,typeName,quoteNo,报价单表Model.get销售顾问(), permit, 报价单表Model, model交车, 顾客记录汇总Model);
                if ("fail".equals(stockResult.getCode())) {
                    logger.error("第三方精品库存扣减失败,流程类型:{}，code：{}，message：{}，obj：{}。permit：{},报价编号：{}",typeName,stockResult.getCode(),stockResult.getMessage(),stockResult.getObj(),permit,quoteNo);
                    TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
                    result.setResult("false");
                    result.setMessage("预约施工单生成失败");
                }
            }

        } catch (Exception e) {
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            logger.error("数据更新异常。", e);
            result.setResult("false");
            result.setMessage("保存失败");
        }
        return result;
    }

    // 扣减第三方精品库存  (typeName:"正常出入账"、“合同修改出入账”、“换票”、“退票”)
    private StockResult reduceThirdBoutiqueStock(Integer type,String typeName,int quoteNo, String salesInfo, String permit, 报价单表Model 报价单表Model, 报价交车表Model model交车, 顾客记录汇总Model 顾客记录汇总Model) {
        StockResult result = new StockResult("success",null,null);

        //开关判断
        String executionPoint = env.getProperty("soa.after.reduce.execution.point");
        if(StringUtils.isNotNullOrBlank(executionPoint)){
            if(! executionPoint.contains("," + typeName + ",")){
                return result;
            }
        }


        List<报价精品详细表Model> thirdBoutiques = setRepository.getThirdBoutiques(quoteNo); // 第三方精品
        // 有第三方精品的时候，请求扣减库存（换票或者合同修改的时候，可能会删除第三方精品，这种情况下，也需要调接口）
        if ("换票".equals(typeName) || "合同修改出入账".equals(typeName) || (null != thirdBoutiques && !thirdBoutiques.isEmpty())) {
            Lsh车型Model carModel = lsh车型Repository.findby车型编号(报价单表Model.get车型编号());
            Lsh库存表Model stockModel = lsh库存表Repository.findLshStockByStockId(报价单表Model.get库存编号());
            PermitCodeModel permitCode = permitCodeRepository.findByPermit(permit);
            用户Model userModel = userRepository.findBy许可And用户名(permit,salesInfo);

            StockParam stockParam = new StockParam();   // 库存参数
            stockParam.setCheckId("");   // 暂时无用的字段（内容随便）
            stockParam.setCompId(permitCode.getCode()); // 公司编号
            stockParam.setSaleBillNo(model交车.get合同号());  // 合同编号
            stockParam.setCustName(顾客记录汇总Model.get顾客姓名());
            stockParam.setCustSort("现结");
            stockParam.setLinkMan(顾客记录汇总Model.get顾客姓名());
            stockParam.setLinkTel(顾客记录汇总Model.get电话号码());
            stockParam.setMobile(顾客记录汇总Model.get电话号码());
            stockParam.setCarSerial(carModel.get级别());
            stockParam.setCarModel(carModel.get车型());
            stockParam.setVincode(stockModel.get车架号());
            if (StringUtils.isNullOrBlank(stockModel.get颜色())) {
                stockParam.setCarColor("*");
            } else {
                stockParam.setCarColor(stockModel.get颜色());
            }
            stockParam.setKeyNo("test");  // 钥匙编号(内容随便)
            stockParam.setBusiMan(userModel.get人员姓名());
            // 设置扩展金额
            stockParam.setExpandAmt(getExpandAmtForBoutique(thirdBoutiques));

            List<StockDetailParam> detailList = new ArrayList<>();  // 库存明细参数
            if (ApprovalWorkFlowEnum.TICKET_RETREAT == type) {
                // 退票的话，设置精品为空
                stockParam.setDetailInfo(null);
            } else {
                for (int i=0; i<thirdBoutiques.size(); i++)  {
                    StockDetailParam detailParam = new StockDetailParam();
                    detailParam.setKeyId(i+1);
                    detailParam.setShopId(thirdBoutiques.get(i).getOriginShopId());
                    detailParam.setShopName(thirdBoutiques.get(i).get名称());
                    detailParam.setUnit(thirdBoutiques.get(i).getOriginShopUnit());
                    detailParam.setQty(thirdBoutiques.get(i).get数量());
                    detailParam.setOrigPrc(thirdBoutiques.get(i).get折后价());
                    detailParam.setSalePrice(thirdBoutiques.get(i).get折后价());
                    detailParam.setRemarks("");
                    detailList.add(detailParam);
                }
                stockParam.setDetailInfo(detailList);
            }

            // 扣减库存url
            String url = GetConfigureInfoUtils.getConfigureInfo("soa.after.url") + "/shop/changeInventoryQty";
            String param = JSON.toJSONString(stockParam); // 参数转化为json
            // 请求库存扣减
            String resultStr = HttpTools.sendPost(url,param,permit,salesInfo);
            logger.info("发送第三方精品库存扣减请求,流程类型:{},请求类型:post,url：{}，param：{}",typeName,url,param);
            result = JSON.parseObject(resultStr,StockResult.class);

            //强制处理{"flag":"-30_2","message":"单据不存在禁止删除!","total":0}为成功
            if(result != null && StringUtils.isNotNullOrBlank(result.getObj())){
                if(! "success".equalsIgnoreCase(result.getCode()) && result.getObj().indexOf("-30_2") > 0){
                    result.setCode("success");
                }
            }
            // 强制处理{"flag":"-30_1","message":"禁止明细为空-1!","total":0}为成功
            if (result !=null && !StringUtils.isNullOrBlank(result.getObj())) {
                if (!"success".equalsIgnoreCase(result.getCode()) && result.getObj().indexOf("-30_1") > 0) {
                    result.setCode("success");
                }
            }

            if (null != result && "success".equals(result.getCode()) ) {
                logger.info("第三方精品库存扣减成功,流程类型:{}。permit：{}，报价编号：{}",typeName,permit,quoteNo);
            }
        }
        return result;
    }

    @Override
    public List<String> getLshProCode(String siCode, String permit) {
        return setRepository.getLshProCode(siCode, permit);
    }

    @Override
    public boolean delCarPolicyByItemNo(String engCode, String itemNo) {
        if (!Strings.isNullOrEmpty(itemNo)) {
            String[] itemArray = itemNo.split(",");
            for (String item : itemArray) {
                try {
                    attachmentPolicyRepository.deleteByProCodeEngAndItemNo(engCode, Integer.valueOf(item));
                } catch (Exception e) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    logger.error("删除厂家随车数据异常。", e);
                    logger.info("删除厂家随车数据异常。", e.getMessage());
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List getCarColorByCarTypeCode(int carTypeCode) {
        return setRepository.getCarColorByCarTypeCode(carTypeCode);
    }

    public List getNoCarIncomeAdjustmentInfo(String permit, String id) {
        return setRepository.getNoCarIncomeAdjustmentInfo(permit, id);
    }

    @Override
    public PageData getJiTuanSourceInfo(GetLSHMarketSettingListRequest request) {
        return setRepository.getJiTuanSourceInfo(request.getPageSize(), request.getPageIndex(), request.channel);
    }

    @Override
    public Boolean saveApprovalUser(PushApprovalItemSettingModel model) {
        ResultData resultData = pushApprovalItemSettingModelCheck(model);
        if ("true".equals(resultData.getResult())) {
            try {
                // 退票的经销商审批人保存
                if (model.getType() == 13) {
                    this.pushApprovalItemSettingRepository.deleteModelByPermitAndTypeAndBrand(model.getPermit(),
                            model.getType(), model.getBrand());
                } else {
                    this.pushApprovalItemSettingRepository.deleteModelByPermitAndType(model.getPermit(), model.getType());
                }
                this.pushApprovalItemSettingRepository.save(model);
                return true;
            } catch (Exception e) {
                logger.error("数据保存异常。", e);
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 经销商保存合同审批人设置
     *
     * @param modelPrivilegeList 前端解析EXCEL的数据
     * @return 标准返回结构
     */
    @Override
    @Transactional
    public ResultData saveApprovalUserList(List<PushApprovalItemSettingModel> modelPrivilegeList) {
        logger.info("saveApprovalUserList参数为" + JsonObjectUtils.writeAsJson(modelPrivilegeList));
        // 重复许可校验，相同的许可只能出现一次
        String re = pushApprovalItemSettingModelListCheck(modelPrivilegeList);
        if (!"00".equals(re)) {
            return new ResultData("false", "不能出现许可重复的数据，重复许可：" + re, null);
        }
        // 各字段数据合法性校验
        for (PushApprovalItemSettingModel model : modelPrivilegeList) {
            ResultData resultData = pushApprovalItemSettingModelCheck(model);
            if (!"true".equals(resultData.getResult())) {
                return resultData;
            }
        }
        try {
            Set<String> permitSet = new HashSet<>();
            Set<Integer> typeSet = new HashSet<>();
            for (PushApprovalItemSettingModel pushApprovalItemSettingModel : modelPrivilegeList) {
                permitSet.add(pushApprovalItemSettingModel.getPermit());
                typeSet.add(pushApprovalItemSettingModel.getType());
            }
            // 当全部审批类型都为3的时候
            if (typeSet.size() == 1 && typeSet.contains(3)) {
                for (String permit : permitSet) {
                    // 按许可，审批类型删除相应的审批设置
                    this.pushApprovalItemSettingRepository.deleteModelByPermitAndType(permit, modelPrivilegeList.get(0).getType());
                    // 按许可，合同修改审批流程删除相应的审批设置
                    this.pushApprovalItemSettingRepository.deleteModelByPermitAndType(permit, 10);
                    // 按许可，换票审批流程删除相应的审批设置
                    this.pushApprovalItemSettingRepository.deleteModelByPermitAndType(permit, 12);

                    Itask基础设置ModelPK itask基础设置ModelPK = new Itask基础设置ModelPK();
                    itask基础设置ModelPK.set许可(permit);
                    itask基础设置ModelPK.set设置项目("订单审批销售行政资源确认");
                    Itask基础设置Model itask基础设置Model = itaskRepository.findOne(itask基础设置ModelPK);
                    if (itask基础设置Model == null) {
                        itask基础设置Model = new Itask基础设置Model();
                        itask基础设置Model.set许可(permit);
                        itask基础设置Model.set设置项目("订单审批销售行政资源确认");
                        itask基础设置Model.set值("0");
                        itaskRepository.save(itask基础设置Model);
                    }
                }
                for (PushApprovalItemSettingModel mo : modelPrivilegeList) {
                    mo.setCreateDate(java.sql.Date.valueOf(LocalDate.now()));
                }
                this.pushApprovalItemSettingRepository.save(modelPrivilegeList);
                // 合同修改审批流程type=10, 换票审批流程type=12，这两个审批流程的审批人，与合同审批流程审批人一致
                // 在导入的时候，根据导入的合同数据，自己生成10与12的数据
                // 合同修改审批流程type=10
                List<PushApprovalItemSettingModel> modelList1 = new ArrayList<>();
                for (PushApprovalItemSettingModel model : modelPrivilegeList) {
                    PushApprovalItemSettingModel newModel;
                    newModel = (PushApprovalItemSettingModel) CloneUtils.deepClone(model);
                    newModel.setType(10);
                    newModel.setId(null);
                    modelList1.add(newModel);
                }
                this.pushApprovalItemSettingRepository.save(modelList1);
                // 换票审批流程type=12
                for (PushApprovalItemSettingModel model : modelPrivilegeList) {
                    PushApprovalItemSettingModel newModel;
                    newModel = (PushApprovalItemSettingModel) CloneUtils.deepClone(model);
                    newModel.setType(12);
                    newModel.setId(null);
                    modelList1.add(newModel);
                }
                this.pushApprovalItemSettingRepository.save(modelList1);
            } else if (permitSet.size() == 1 && typeSet.size() == 1 && typeSet.contains(13)) { // 经销商批量保存的处理
                for (PushApprovalItemSettingModel aSetMo : modelPrivilegeList) {
//                    if (aSetMo.getId() == null) { // 如果新纪录，设置时间
//                        aSetMo.setCreateDate(java.sql.Date.valueOf(LocalDate.now()));
//                        aSetMo.setModifydate(java.sql.Date.valueOf(LocalDate.now()));
//                    } else {
//                        // 判断原创建时间是否为空
//                        java.sql.Date createDate = pushApprovalItemSettingRepository.findOne(aSetMo.getId()).getCreateDate();
//                        if (createDate == null) { // 原记录创建时间为空，设置为当前时间
//                            aSetMo.setCreateDate(java.sql.Date.valueOf(LocalDate.now()));
//                        } else { // 非空，保留
//                            aSetMo.setCreateDate(createDate);
//                        }
//                    }
//                    aSetMo.setModifydate(java.sql.Date.valueOf(LocalDate.now()));
                    // 目前前端有BUG，会产生重复数据，前端不好升级，后台帮忙处理
                    // 将相应的数据删除
                    this.pushApprovalItemSettingRepository.deleteModelByPermitAndType(aSetMo.getPermit(), aSetMo.getType());
                    aSetMo.setCreateDate(java.sql.Date.valueOf(LocalDate.now()));
                }
                this.pushApprovalItemSettingRepository.save(modelPrivilegeList);
            }
            return new ResultData("true", null, null);
        } catch (Exception e) {
            logger.error("数据保存异常。", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultData("false", "保存审批人异常", null);
        }
    }

//    private List<PushApprovalItemSettingModel> priModelToNormalModel(List<PushApprovalItemSettingPrivilegeModel> priModelList) {
//        List<PushApprovalItemSettingModel> approvalItemList = new ArrayList<>();
//        for (PushApprovalItemSettingPrivilegeModel pPriModel : priModelList) {
//            PushApprovalItemSettingModel pModel = new PushApprovalItemSettingModel();
//            pModel.setId(pPriModel.getId());
//            pModel.setPermit(pPriModel.getPermit());
//            pModel.setType(pPriModel.getType());
//            pModel.setBrand(null);
//            pModel.setStep1(pPriModel.getStep1());
//            pModel.setStep2(pPriModel.getStep2());
//            pModel.setStep3(pPriModel.getStep3());
//            pModel.setStep4(pPriModel.getStep4());
//            pModel.setStep5(pPriModel.getStep5());
//            pModel.setStep6(pPriModel.getStep6());
//            pModel.setStep7(pPriModel.getStep7());
//            pModel.setStep8(pPriModel.getStep8());
//            pModel.setStep9(pPriModel.getStep9());
//            approvalItemList.add(pModel);
//        }
//        return approvalItemList;
//    }

//    private boolean validateRole(String role) {
//        return "销售经理".equals(role) || "销售主管".equals(role) || "总经理".equals(role) || "RMB".equals(role)
//                || "RCOO".equals(role) || "RD".equals(role) || "CTA".equals(role) || "展厅经理".equals(role);
//    }

    /**
     * 判断modelList中有没有重复的许可，正常情况下不允许出现
     *
     * @param modelList 前端解析出Excel中的数据
     * @return 如果没有重复许可，返回"00"，如果有，返回第一个重复的许可
     */
    private String pushApprovalItemSettingModelListCheck(List<PushApprovalItemSettingModel> modelList) {
        Map<String, Integer> map = new HashMap<>();
        for (PushApprovalItemSettingModel model : modelList) {
            String permit = model.getPermit();
            if (map.get(permit) != null) {
                return permit;
            } else {
                map.put(permit, 1);
            }
        }
        return "00";
    }

    private ResultData pushApprovalItemSettingModelCheck(PushApprovalItemSettingModel model) {
        String permit = model.getPermit();
        Integer type = model.getType();
//        String brand = model.getBrand();
        String user1 = model.getStep1();
        String user2 = model.getStep2();
        String user3 = model.getStep3();
        String user4 = model.getStep4();
        String user5 = model.getStep5();
        String user6 = model.getStep6();
        String user7 = model.getStep7();
        String user8 = model.getStep8();
        String user9 = model.getStep9();
        String remark = model.getRemark();

        // permit校验
        List<Lsh经销商表Model> l = lsh经销商表Repository.findAll();
        if (l.size() == 0) {
            return new ResultData("false", "经销商表没数据", null);
        }
        Boolean b = false;
        if (permit == null || permit.length() == 0) {
            return new ResultData("false", "许可为空或空串", null);
        } else {
            model.setPermit(permit.trim());
            for (Lsh经销商表Model m : l) {
                if (permit.equals(m.getBmbs())) {
                    b = true;
                    break;
                }
            }
        }
        if (!b) {
            return new ResultData("false", "没找到对应许可: " + permit, null);
        }
        // type检验
        if (type <= 0 || type >= 14) {
            return new ResultData("false", "不存在的审批类型", null);
        }
        // brand校验
//        if (brand == null || brand.length() == 0) {
//            resultData.setMessage("品牌为空或空串");
//            return resultData;
//        } else if (!"MB".equals(brand)
//                && !"MM".equals(brand)
//                && !"AMG".equals(brand)
//                && !"smart".equals(brand)
//                && brand != null
//                ) {
//            resultData.setMessage("品牌非法");
//            return resultData;
//        }
        // 审批人校验
        if ((user1 != null && user1.length() == 0) || (user2 != null && user2.length() == 0)
                || (user3 != null && user3.length() == 0) || (user4 != null && user4.length() == 0)
                || (user5 != null && user5.length() == 0) || (user6 != null && user6.length() == 0)
                || (user7 != null && user7.length() == 0) || (user8 != null && user8.length() == 0)
                || (user9 != null && user9.length() == 0)) {
            return new ResultData("false", permit + "审批人不能为空串", null);
        }
        List<String> tempList = new ArrayList<>();
        Integer maxStepIndex = 0;
        if (user1 == null) {
            return new ResultData("false", permit + "一级审批人不合法", null);
        } else {
            tempList.add(user1);
            tempList.add(user2);
            tempList.add(user3);
            tempList.add(user4);
            tempList.add(user5);
            tempList.add(user6);
            tempList.add(user7);
            tempList.add(user8);
            tempList.add(user9);
            for (int i = 0; i < tempList.size(); i++) {
                if (tempList.get(i) != null) {
                    maxStepIndex = i;
                }
            }
            // 如果第二审批人至倒数第二审批人中，任何一个人为空，可以认为审批流程不合理
            for (int i = 1; i < maxStepIndex; i++) {
                if (tempList.get(i) == null) {
                    return new ResultData("false", permit + "审批流程设置不合理", null);
                }
            }
            // 将所有用户名前后的空格去掉
            for (int i = 0; i < maxStepIndex + 1; i++) {
                if (tempList.get(i) != null) {
                    tempList.set(i, tempList.get(i).trim());
                }
            }
        }
        // 查看step中出现的用户名在审批流程中的有效性
        List<用户Model> positionList = userRepository.findAll();
        String[] roles = new String[maxStepIndex + 1];
        for (int i = 0; i < tempList.size(); i++) {
            String userName = tempList.get(i);
            //审批人职位判断
            if (userName != null) {
                if (userName.endsWith("_")) {
                    return new ResultData("false","审批人职位和审批人账号不能为同时空",null);
                }
                if (isRoleName(userName)) { // 人名审批
                    roles[i] = userRepository.findRoleByUsername(userName);
                    if (ApprovalUtils.isContractType(type) && i == 0
                            && roles[i] != null && !"销售顾问".equals(roles[i].trim())) { // 一级审批人角色非销售顾问
                        return new ResultData("false", "一级审批人账号不是销售顾问", null);
                    }
                    if (roles[i] == null) { // 审批人对应的角色为空
                        return new ResultData("false", "审批人" + userName + "没有设置角色", null);
                    }
                } else { // 组织架构审批
                    if (userName.contains("_")) {
                        if (ApprovalUtils.isContractType(type) &&
                                i == 0 && !"销售顾问".equals(userName.split("_")[1])) { // 一级审批人角色非销售顾问
                            return new ResultData("false", "一级审批人账号不是销售顾问", null);
                        }
                        Set poSet = positionList.stream().map(u -> u.get所属部门() + "_" + u.get角色()).collect(Collectors.toSet());
                        if (!poSet.contains(userName)) {
                            return new ResultData("false", "设置的组织架构审批" + userName + "在系统中找不到对应的人", null);
                        }
                    } else {
                        return new ResultData("false", "传入的参数格式不合法，不是【部门_岗位】的形式", null);
                    }
                }
            }
        }
        // remark校验
        if (remark != null && remark.length() > 100) {
            return new ResultData("false", "备注过长", null);
        }
        return new ResultData("true", "正常", null);
    }

//    private ResultData approvalPrivilegeCheck(PushApprovalItemSettingPrivilegeModel priModel) {
//        logger.info("合同审批导入approvalPrivilegeCheck，参数为" + JsonObjectUtils.writeAsJson(priModel));
//        String errMsg = "合同审批人导入时，Model校验失败";
//        try {
//            // 检验除权限之外的数据
//            List<PushApprovalItemSettingPrivilegeModel> pList = new ArrayList<>();
//            pList.add(priModel);
//            List<PushApprovalItemSettingModel> nList = priModelToNormalModel(pList);
//            PushApprovalItemSettingModel model = nList.get(0);
//
//            ResultData resultData = pushApprovalItemSettingModelCheck(model);
//
//            // 检验不通过时返回
//            if ("false".equals(resultData.getResult())) {
//                return resultData;
//            }
//
//            Integer type = priModel.getType();
//            if (type == 13) {
//                return resultData;
//            }
//            if (type == 3) { // 合同导入的时候才校验权限与保存
//                String permit = priModel.getPermit();
//                List<String> userList = new ArrayList<>();
//                // 初始化审批人list
//                userList.add(priModel.getStep1());
//                userList.add(priModel.getStep2());
//                userList.add(priModel.getStep3());
//                userList.add(priModel.getStep4());
//                userList.add(priModel.getStep5());
//                userList.add(priModel.getStep6());
//                userList.add(priModel.getStep7());
//                userList.add(priModel.getStep8());
//                userList.add(priModel.getStep9());
//                // 初始化权限list
//                List<String> priList = new ArrayList<>();
//                priList.add(priModel.getPrivilege1());
//                priList.add(priModel.getPrivilege2());
//                priList.add(priModel.getPrivilege3());
//                priList.add(priModel.getPrivilege4());
//                priList.add(priModel.getPrivilege5());
//                priList.add(priModel.getPrivilege6());
//                priList.add(priModel.getPrivilege7());
//                priList.add(priModel.getPrivilege8());
//                priList.add(priModel.getPrivilege9());
//                // 删除相应的Itask基础设置内与审批相关的SNP设置
//                this.itaskRepository.deleteContractItemByPermit(permit);
//                for (int i = 0; i < priList.size(); i++) { // 根据审批人设置保存数据
//                    String user = userList.get(i);
//                    Itask基础设置Model iModel = new Itask基础设置Model();
//                    iModel.set许可(permit);
//                    iModel.set设置项目(ApprovalUtils.STEP + (i + 1));
//                    if (user != null) { // 审批人有数据，trim()后检验
//                        String pri = priList.get(i).trim();
//                        BigDecimal bd;
//                        if ("must".equals(pri)) { // 如果为must，则保存
//                            iModel.set值(pri);
//                        } else { // 不为must，就是Double权限
//                            try {
//                                bd = new BigDecimal(pri);
//                                iModel.set值(bd.toString());
//                            } catch (NumberFormatException e) {
//                                errMsg = "填入的权限不是合法的小数:" + pri;
//                                throw e;
//                            }
//                        }
//                        itask基础设置Repository.save(iModel);
//                    } // step内没有审批人时，与前台开发人员协定是无效数据
//                }
//            } // 其他流程不用管
//            return new ResultData("true", "正常", null);
//        } catch (Exception e) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            logger.error(errMsg, e);
//            return new ResultData("false", errMsg, null);
//        }
//    }

    @Override
    public boolean delDealerAttachmentPloicy(DelDealerAttachmentPloicyRequest request) {
        boolean flag;
        try {
            dApilicyRepository.delDealerAttachmentPloicy(request.itemCount, request.permit);
            flag = true;
        } catch (Exception e) {
            flag = false;
            logger.error("数据删除异常。", e);
        }
        return flag;
    }

    @Override
    public List getCarLastUpdateTime() {
        return setRepository.getCarLastUpdateTime();
    }

    @Override
    public PageData getInvoicesList(purposeRequest purposeRequest, String dealer) {
        logger.info("getInvoicesList参数为:" + JsonObjectUtils.writeAsJson(purposeRequest));
        return setRepository.getInvoicesList(purposeRequest, dealer);
    }


    @Override
    public List getInvoicesdetail(String VIN) {
        return setRepository.getInvoicesdetail(VIN);
    }

    @Override
    @Transactional
    public ResultData updateInvoicesState(InvoicesState invoicesState, String username, String permit) {
        logger.info("updateInvoicesState传入参数为:" + JsonObjectUtils.writeAsJson(invoicesState));
        String errMsg = "调车开票异常";
        try {
            //取到库存表数据
            Lsh库存表Model stockMo = lsh库存表Repository.findLshRecordByVin(invoicesState.VIN);
            // 正常流程中，应该是财务状态从“等待开调车增值票/付款” -> “调车发票完毕”
            if (!"等待开调车增值票/付款".equals(stockMo.get调车财务状态())) { // 如果此时不处理待开票状态
                errMsg = "此车已经开过票";
                throw new Exception();
            }
            stockMo.set调车财务状态("调车发票完毕");
            lsh库存表Repository.save(stockMo);
            Integer stockCode = stockMo.get库存编号();//获取库存编号
            String name调入经销商 = stockMo.get调入经销商();
            //取到Car表数据
            List<CarTransferLogModel> carTransferLogModelList = carTransferLogRepository.findByStockId(stockCode);
            CarTransferLogModel transMo = carTransferLogModelList.get(0);
            transMo.setFinancialStatus("调车发票完毕");
            java.sql.Date currDate = new java.sql.Date(DateFormatUtils.getFormatDate("yyyy-MM-dd", new Date()).getTime());//获取当前日
            java.sql.Date invoiceDate = java.sql.Date.valueOf(LocalDate.parse(invoicesState.invoiceDate));//获取传入时间
            if (invoicesState.invoiceDate.length() != 0 && !invoicesState.invoiceDate.equals("")) {
                transMo.setInvoiceIssuingDate(invoiceDate);
            } else {
                transMo.setInvoiceIssuingDate(currDate);
            }
            transMo.setInvoiceIssuingUser(username);
            transMo.setOutInvoiceRemark(invoicesState.remark);
            carTransferLogRepository.save(transMo);
            //获取接收人
            String user = messageSettingRepository.finduser(name调入经销商, "2", "1");
            if (user != null && !user.equals("")) {
                String receiveUser = messageSettingRepository.finduser(name调入经销商, "2", "1");
                if (receiveUser != null && !receiveUser.equals("")) {
                    Integer carID = stockMo.get车型编号();
                    //获取车型
                    String carType = lsh车型Repository.findby车型编号(carID).get车型详细();
                    //获取调出经销商
                    String bid = stockMo.get调出经销商();
                    String bname = lsh经销商表Repository.findNameByPermit(bid);
                    LshMsgUtils.getLshMsg(permit, username, name调入经销商, receiveUser, "调车调入", MessageContext.getPostCarTransferSuss(
                            transMo.getCustomName(), bname, carType), null, null);
                }
            }
            return new ResultData("true", null, null);
        } catch (Exception e) {
            logger.error(errMsg, e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            return new ResultData("false", errMsg, null);
        }
    }

    @Override
    @Transactional
    public boolean updateInvoicesStateN(InvoicesState invoicesState, String liveuername) throws Exception {
        logger.warn("传入参数:日期,VIN",invoicesState.invoiceDate,invoicesState.VIN);
        String vin = invoicesState.VIN;//获取传来的VIN
        Timestamp nowdate = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date());//获取当前时间
        //java.sql.Date nowdate1=  java.sql.Date.valueOf(LocalDate.parse(invoicesState.invoiceDate));//传入时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
        //取到库存表数据
        Lsh库存表Model lsh库存表Model = lsh库存表Repository.findLshRecordByVin(vin);
        //获取报价单表数据
        报价单表Model 报价单表Model = 报价单表Repository.findBy报价编号(lsh库存表Model.get报价编号());
        //获取报价交车表数据
        报价单表Model 报价单表Model2 = 报价单表Repository.getListByInitQuoteNumber(报价单表Model.get初始报价单号()).get(0);
        报价单表Model2.set是否还原点("是");
        报价单表Model2.set还原点创建时间(nowdate);
        报价单表Repository.save(报价单表Model2);

        Integer 顾客编号 = 报价单表Model2.get顾客编号();
        报价交车表Model 报价交车表Model = 报价交车表Repository.findby编号(报价单表Model2.get交车());
        if (invoicesState.invoiceDate.length() != 0 && !invoicesState.invoiceDate.equals("")) {
            String time = sdf1.format(new Date());
            Date dt = sdf.parse(invoicesState.invoiceDate + " " + time);
            报价交车表Model.set开票时间(DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", dt));//传入时间
        } else {
            报价交车表Model.set开票时间(nowdate);
        }


        Integer 订单编号 = 报价单表Model2.get订单编号();
        logger.warn("开票获取订单编号=",订单编号);

        报价订单表Model quotationOrderModel = 报价订单表Repository.findOne(订单编号);
        quotationOrderModel.set订单状态("开票C");
        报价订单表Repository.save(quotationOrderModel);

        报价交车表Model.set开票财务备注(invoicesState.remark);
        报价交车表Repository.save(报价交车表Model);

        //修改新车销售状态
        顾客记录汇总Model 顾客记录汇总Model = 顾客记录汇总Repository.findCusByCustomerID(顾客编号);

        /**
         *
         */
        if (顾客记录汇总Model!=null&&顾客记录汇总Model.get新车销售状态()!=null&&顾客记录汇总Model.get新车销售状态()<17){
            顾客记录汇总Model.set新车销售状态(17);
            顾客记录汇总Repository.save(顾客记录汇总Model);
        }

        //修改进店日志记录 --lc
        Integer quotedPriceCodeOrVin = lsh库存表Model.get报价编号();//报价编号
        String id = repository顾客进店记录表.findBJBH(quotedPriceCodeOrVin.toString());
        if(id !=null&&!id.trim().equals("")) {
            顾客进店记录表Model model顾客进店记录表 = repository顾客进店记录表.findOneByQuotedPriceCode(
                    Integer.valueOf(id));
            String nowDay = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            if (model顾客进店记录表 != null || !nowDay.equals(new SimpleDateFormat("yyyy-MM-dd").format(model顾客进店记录表.get进店日期()))) {
            /*model顾客进店记录表.set到店目的("办手续");
            model顾客进店记录表.set客户级别("无评级:已经订单或交车");*/
                TrafficLogUtils.updateTrafficLogModel(model顾客进店记录表, 8);
                repository顾客进店记录表.save(model顾客进店记录表);
            }
        }

        // 判断车型是否改变，及相关处理
        approvalService.updateOldOrNewRecord(报价单表Model2,99);
        return true;
    }

    @Override
    @Transactional
    public boolean updateInvoicesStateT(InvoicesState invoicesState, String liveuername) {
        logger.info("开始调用退票确认接口，车架号：{}",invoicesState.VIN);
        try {
            String vin = invoicesState.VIN;//获取传来的VIN
            Timestamp nowdate = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date());//获取当前时间
            //java.sql.Date nowdate1=  java.sql.Date.valueOf(LocalDate.parse(invoicesState.invoiceDate));//传入时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
            //取到库存表数据
            Lsh库存表Model lsh库存表Model = lsh库存表Repository.findLshRecordByVin(vin);
            if (lsh库存表Model == null) {
                logger.warn("找不到库存, vin={}", vin);
                return false;
            }

            if (lsh库存表Model.get报价编号() == null) {
                logger.warn("找不到库存关联报价编号, vin={}", vin);
                return false;
            }

            //获取报价单表数据
            报价单表Model 报价单表Model = 报价单表Repository.findBy报价编号(lsh库存表Model.get报价编号());
            //获取报价交车表数据
            报价单表Model 报价单表Model2 = 报价单表Repository.getListByInitQuoteNumber(报价单表Model.get初始报价单号()).get(0);
            报价单表Model2.set是否还原点("是");
            报价单表Model2.set还原点创建时间(nowdate);
            报价单表Repository.save(报价单表Model2);

            Integer 顾客编号 = 报价单表Model2.get顾客编号();
            报价交车表Model 报价交车表Model = 报价交车表Repository.findby编号(报价单表Model2.get交车());
            if (invoicesState.invoiceDate.length() != 0 && !invoicesState.invoiceDate.equals("")) {
                String time = sdf1.format(new Date());
                Date dt = sdf.parse(invoicesState.invoiceDate + " " + time);
                报价交车表Model.set退票时间(DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", dt));//传入时间
            } else {
                报价交车表Model.set退票时间(nowdate);
            }

            Integer 订单编号 = 报价单表Model2.get订单编号();
            // 新需求 改为 订单C
            报价订单表Repository.updateOrderStatusById(订单编号, "订单C");
            报价交车表Model.set退票财务备注(invoicesState.remark);
            报价交车表Repository.save(报价交车表Model);

            //修改新车销售状态
            顾客记录汇总Model 顾客记录汇总Model = 顾客记录汇总Repository.findCusByCustomerID(顾客编号);
            顾客记录汇总Model.set新车销售状态(13);  //
            顾客记录汇总Repository.save(顾客记录汇总Model);

            // 第三方精品
            String typeName = "退票";
            TBoutiqueCallCheckModel checkModel = tBoutiqueCallCheckRepository.findBycontroactNUm(报价交车表Model.get合同号());
            if (checkModel == null || (DefaultValueConstant.CHECK_CAR_SOURCE_HOLD.equals(checkModel.getCheckStatus()) && ApprovalWorkFlowEnum.TICKET_RETREAT == checkModel.getOrderType())) {
                // 精品信息确认维护表
                if (null == checkModel) {
                    checkModel = new TBoutiqueCallCheckModel();
                    checkModel.setQuotaId(报价单表Model2.get报价编号().toString());
                    checkModel.setContractNum(报价交车表Model.get合同号());
                    checkModel.setCheckStatus(DefaultValueConstant.CHECK_CAR_SOURCE_PASS); // 设置为已确认
                    checkModel.setScName(报价单表Model2.get销售顾问());
                    checkModel.setPermit(报价单表Model2.get许可());
                    checkModel.setOrderType(ApprovalWorkFlowEnum.TICKET_RETREAT);
                    checkModel.setCreatedTime(DateUtils.getCurrentTimestamp());
                } else {
                    checkModel.setCheckStatus(DefaultValueConstant.CHECK_CAR_SOURCE_PASS); // 设置为已确认
                    checkModel.setUpdateTime(DateUtils.getCurrentTimestamp());
                }
                tBoutiqueCallCheckRepository.save(checkModel);

                // 调用三方精品库存系统
                StockResult stockResult = reduceThirdBoutiqueStock(ApprovalWorkFlowEnum.TICKET_RETREAT,typeName,报价单表Model2.get报价编号(), 报价单表Model2.get销售顾问(), 报价单表Model2.get许可(), 报价单表Model2, 报价交车表Model, 顾客记录汇总Model);
                if ("fail".equals(stockResult.getCode())) {
                    logger.error("第三方精品库存扣减失败,流程类型:{},code：{},message：{},obj：{}。permit：{},报价编号：{}", typeName,stockResult.getCode(), stockResult.getMessage(), stockResult.getObj(), 报价单表Model2.get许可(), 报价单表Model2.get报价编号());
                    TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
            }


        } catch (Exception e) {
            logger.error("数据保存异常。", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    @Override
    @Transactional
    public boolean updateInvoicesStateH(InvoicesState invoicesState, String liveuername) {
        logger.info("开始调用换票确认接口，车架号：{}",invoicesState.VIN);
        try {
            String vin = invoicesState.VIN;//获取传来的VIN
            logger.warn("传入参数:日期,VIN",invoicesState.invoiceDate,invoicesState.VIN);
            Timestamp nowdate = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date());//获取当前时间
            //java.sql.Date nowdate1=  java.sql.Date.valueOf(LocalDate.parse(invoicesState.invoiceDate));//传入时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
            //取到库存表数据
            Lsh库存表Model lsh库存表Model = lsh库存表Repository.findLshRecordByVin(vin);
            //获取报价单表数据
            报价单表Model 报价单表Model = 报价单表Repository.findBy报价编号(lsh库存表Model.get报价编号());
            //获取报价交车表数据
            报价单表Model 报价单表Model2 = 报价单表Repository.getListByInitQuoteNumber(报价单表Model.get初始报价单号()).get(0);
            报价单表Model2.set是否还原点("是");
            报价单表Model2.set还原点创建时间(nowdate);
            报价单表Repository.save(报价单表Model2);


            Integer 顾客编号 = 报价单表Model2.get顾客编号();
            报价交车表Model 报价交车表Model = 报价交车表Repository.findby编号(报价单表Model2.get交车());
            if (invoicesState.invoiceDate.length() != 0 && !invoicesState.invoiceDate.equals("")) {
                String time = sdf1.format(new Date());
                Date dt = sdf.parse(invoicesState.invoiceDate + " " + time);
                报价交车表Model.set换票时间(DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", dt));//传入时间
            } else {
                报价交车表Model.set换票时间(nowdate);
            }


            Integer 订单编号 = 报价单表Model2.get订单编号();
            logger.warn("换票获取订单编号=",订单编号);
//            报价订单表Repository.updateOrderStatusById(订单编号, "开票C");  // 新财务不需要设置该状态
            报价交车表Model.set换票财务备注(invoicesState.remark);
            报价交车表Repository.save(报价交车表Model);


            //修改新车销售状态
            顾客记录汇总Model 顾客记录汇总Model = 顾客记录汇总Repository.findCusByCustomerID(顾客编号);
            顾客记录汇总Model.set新车销售状态(17);
            顾客记录汇总Repository.save(顾客记录汇总Model);

            // 第三方精品
            String typeName = "换票";
            TBoutiqueCallCheckModel checkModel = tBoutiqueCallCheckRepository.findBycontroactNUm(报价交车表Model.get合同号());
            if(checkModel == null){
               logger.warn("合同号={}不存在精品确认记录。", 报价交车表Model.get合同号());
            }else if((DefaultValueConstant.CHECK_CAR_SOURCE_HOLD.equals(checkModel.getCheckStatus())
                    && ApprovalWorkFlowEnum.TICKET_CHANG == checkModel.getOrderType())){
                logger.warn("单子最新状态是换票状态且待确认状态。合同号={}", 报价交车表Model.get合同号());
            }

            if (checkModel == null ||(DefaultValueConstant.CHECK_CAR_SOURCE_HOLD.equals(checkModel.getCheckStatus())
                    && ApprovalWorkFlowEnum.TICKET_CHANG == checkModel.getOrderType())) {
                // 精品信息确认维护表
                if (null == checkModel) {
                    checkModel = new TBoutiqueCallCheckModel();
                    checkModel.setQuotaId(报价单表Model2.get报价编号().toString());
                    checkModel.setContractNum(报价交车表Model.get合同号());
                    checkModel.setCheckStatus(DefaultValueConstant.CHECK_CAR_SOURCE_PASS); // 设置为已确认
                    checkModel.setScName(报价单表Model2.get销售顾问());
                    checkModel.setPermit(报价单表Model2.get许可());
                    checkModel.setOrderType(ApprovalWorkFlowEnum.TICKET_CHANG);
                    checkModel.setCreatedTime(DateUtils.getCurrentTimestamp());
                } else {
                    checkModel.setCheckStatus(DefaultValueConstant.CHECK_CAR_SOURCE_PASS); // 设置为已确认
                    checkModel.setUpdateTime(DateUtils.getCurrentTimestamp());
                }
                tBoutiqueCallCheckRepository.save(checkModel);

                // 调用三方精品库存系统
                if(logger.isDebugEnabled()){
                    logger.debug("开始调用第三方精品系统。合同号={}", 报价交车表Model.get合同号());
                }
                StockResult stockResult = reduceThirdBoutiqueStock(0,typeName,报价单表Model2.get报价编号(), 报价单表Model2.get销售顾问(), 报价单表Model2.get许可(), 报价单表Model2, 报价交车表Model, 顾客记录汇总Model);
                if ("fail".equals(stockResult.getCode())) {
                    logger.error("第三方精品库存扣减失败,流程类型:{},code：{},message：{},obj：{}。permit：{},报价编号：{}",typeName,stockResult.getCode(),stockResult.getMessage(),stockResult.getObj(),报价单表Model2.get许可(),报价单表Model2.get报价编号());
                    TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
                   return false;
                }
            }

        } catch (Exception e) {
            logger.error("数据更新异常。", e);

            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
//            LogFactory.getLog(SetServiceImpl.class).info(e.getStackTrace());
            return false;
        }
        return true;
    }

    @Override
    @Transactional
    public boolean sendInsInfo(SendInsInfo sendInsInfo, String permit, String userName) {
        boolean flag = false;
        try {
            if ("新车出入账".equals(sendInsInfo.state)) {
                String news = "客户" + sendInsInfo.cusName + "先生/女士，电话号码" + sendInsInfo.teleNumber + "，财务新车出入账完成，请跟进";
                //极光推送
                JsonObject json = JsonObjectUtils.getJsonObject("财务", null, null, sendInsInfo.teleNumber, null, sendInsInfo.salesCode);
                List sendName = Lists.newArrayList();
                sendName.add(sendInsInfo.salesCode);
                JPush.SendPushITaskForAndroidAndIos(news, news, json, sendName);
                //存入lsh数据库
                LshMsgUtils.getLshMsg(permit, userName, permit, sendInsInfo.salesCode, "财务", news,
                        userName, sendInsInfo.teleNumber);
            }
            if ("新车开票".equals(sendInsInfo.state)) {
                String news = "客户" + sendInsInfo.cusName + "先生/女士，电话号码" + sendInsInfo.teleNumber + "，财务新车开票完成，请跟进";
                //极光推送
                JsonObject json = JsonObjectUtils.getJsonObject("财务", null, null, sendInsInfo.teleNumber, null, sendInsInfo.salesCode);
                List sendName = Lists.newArrayList();
                sendName.add(sendInsInfo.salesCode);
                JPush.SendPushITaskForAndroidAndIos(news, news, json, sendName);
                //存入lsh数据库
                LshMsgUtils.getLshMsg(permit, userName, permit, sendInsInfo.salesCode, "财务", news,
                        userName, sendInsInfo.teleNumber);
            } else if ("退票".equals(sendInsInfo.state)) {
                String news = "客户" + sendInsInfo.cusName + "先生/女士，电话号码" + sendInsInfo.teleNumber + "，财务退票完成，请查看。";
                //极光推送
                JsonObject json = JsonObjectUtils.getJsonObject("财务", null, null, sendInsInfo.teleNumber, null, sendInsInfo.salesCode);
                List sendName = Lists.newArrayList();
                sendName.add(sendInsInfo.salesCode);
                JPush.SendPushITaskForAndroidAndIos(news, news, json, sendName);
                //存入lsh数据库
                LshMsgUtils.getLshMsg(permit, userName, permit, sendInsInfo.salesCode, "财务", news,
                        userName, sendInsInfo.teleNumber);
            } else if ("换票".equals(sendInsInfo.state)) {
                String news = "客户" + sendInsInfo.cusName + "先生/女士，电话号码" + sendInsInfo.teleNumber + "，财务换票完成，请查看。";
                //极光推送
                JsonObject json = JsonObjectUtils.getJsonObject("财务", null, null, sendInsInfo.teleNumber, null, sendInsInfo.salesCode);
                List sendName = Lists.newArrayList();
                sendName.add(sendInsInfo.salesCode);
                JPush.SendPushITaskForAndroidAndIos(news, news, json, sendName);
                //存入lsh数据库
                LshMsgUtils.getLshMsg(permit, userName, permit, sendInsInfo.salesCode, "财务", news,
                        userName, sendInsInfo.teleNumber);
            }
            flag = true;
        } catch (Exception e) {
            logger.error("财务消息发送异常", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }
        return flag;
    }

    public ResultData getItaskDealerInfo(String permit, String username) {
        ResultData rd = new ResultData();
        String flag = null;
        String msg = null;
        PageData pg = new PageData();
        List itemlist = new ArrayList();
        Map itemMap1 = new HashMap();
        try {

            Itask基础设置ModelPK pk1 = new Itask基础设置ModelPK();
            pk1.set许可(permit);
            pk1.set设置项目("金融审批自动通过");
            Itask基础设置Model item1 = itask基础设置Repository.findOne(pk1);


            Itask基础设置ModelPK pk2 = new Itask基础设置ModelPK();
            pk2.set许可(permit);
            pk2.set设置项目("保险审批自动通过");
            Itask基础设置Model item2 = itask基础设置Repository.findOne(pk2);


            itemMap1.put("许可", permit);

            if (item1 != null && item1.get值() != null) {
                if ("1".equals(item1.get值())) {
                    itemMap1.put("金融", "自动");
                } else {
                    itemMap1.put("金融", "不自动");
                }
            } else {
                itemMap1.put("金融", "未设置");
            }

            if (item2 != null && item2.get值() != null) {
                if ("1".equals(item2.get值())) {
                    itemMap1.put("保险", "自动");
                } else {
                    itemMap1.put("保险", "不自动");
                }
            } else {
                itemMap1.put("保险", "未设置");
            }
            msg = "获取itask基础设置表查询成功";
            flag = "true";
        } catch (Exception e) {
            logger.error(String.format("许可为： %s 的店，获取itask基础设置表出错", permit));
            msg = "获取itask基础设置表查询出错";
            flag = "false";
        }


        itemlist.add(itemMap1);
        pg.setData(itemlist);
        pg.setTotal(itemlist.size());
        rd.setMessage(msg);
        rd.setPageData(pg);
        rd.setResult(flag);
        return rd;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    @Override
    public String  importSet(List<Map<String,Object>> list,String permit,String userName,Integer reportType) throws Exception{
        int saveCount = 0;
        int updateCount = 0;
        if(null == list || list.size() <=0){
            return "新增SI：" + saveCount + ",更新SI：" + updateCount;
        }
        //将导入的数据转换成VO
        List<Object> objList = BeanUtils.mapToObjectList(list,SiImportVo.class);
        for (Object obj:objList) {
            SiImportVo vo = (SiImportVo)obj;
            if(StringUtils.isNullOrBlank(vo.getSiType()) && StringUtils.isNullOrBlank(vo.getVin()) && StringUtils.isNullOrBlank(vo.getProductionNo())){
                continue;
            }
            //构建入库modelList并且入库数据补全
            IncomeAdjustmentModel model  = new IncomeAdjustmentModel();
            //2根据生产号查询库存ID、车型ID
            Lsh库存表Model stock = lsh库存表Repository.findLshRecordByProId(vo.getProductionNo());
            model.setCarCode(null == stock?null:stock.get车型编号());
            model.setStockCode(null == stock?null:stock.get库存编号());
            //其他属性
            model.setLastUpdateUser(userName);
            model.setPermit(permit);
            model.setType(null == SelectBoxOptionEnum.SIType.getIndex(vo.getSiType())?"1":SelectBoxOptionEnum.SIType.getIndex(vo.getSiType()).toString());
            model.setLastUpdateDate(DateFormatUtils.parseStrToSqlDate(new Date()));
            model.setAdjustDate(DateFormatUtils.parseStrToSqlDate(DateFormatUtils.getFormatDate(vo.getSiDate(),DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD)));
            model.setValidStartDate(DateFormatUtils.parseStrToSqlDate(DateFormatUtils.getDateByMonthFirstDay(DateFormatUtils.getFormatDate(vo.getSiDate(),DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD))));
            model.setValidEndDate(DateFormatUtils.parseStrToSqlDate(DateFormatUtils.getDateByMonthLastDay(DateFormatUtils.getFormatDate(vo.getSiDate(),DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD))));
            //构建率值
            model = buildSiModel(model,vo,reportType, stock);
            //检测库存ID是否存在DB用以切换持久化方式
            IncomeAdjustmentModel income = isInsertSi(vo.getSiType(),model.getStockCode(),permit,model.getCarCode());
            if (null == income){
                saveCount ++;
                inAdjustmentRepository.save(model);
            }else{
                updateCount ++;
                model.setId(income.getId());
                inAdjustmentRepository.save(buildUpdateSiModel(model,income,reportType));
            }
        }
        return "新增SI：" + saveCount + ",更新SI：" + updateCount;
    }


    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    public String importBmbsSet(List<Map<String, Object>> list, String permit, String userName) throws Exception {
        int saveCount = 0;
        int updateCount = 0;
        Map<String,Object> siSettingMap = Maps.newHashMap();//保存si基本信息
        if(null == list || list.size() <=0){
            return "新增SI：" + saveCount + ",更新SI：" + updateCount;
        }
        //将导入的数据转换成VO
        List<Object> objList = BeanUtils.mapToObjectList(list,SibmbsImportVo.class);
        int index =0;
        Integer pnum = getMaxPnum();
        for (Object obj:objList) {
            SibmbsImportVo vo = (SibmbsImportVo) obj;
            //保存bmbs_setting记录
            if(!validSibmbs(vo)){
                continue;
            }
            //时间特殊处理
            String setDate = vo.getConfirmDate();//StringUtils.isNullOrBlank(vo.getConfirmDate());
            //确保vin存在且状态是零售已卖否则跳过
            Lsh库存表Model stock = lsh库存表Repository.findLshRecordByVin(vo.getVin());
            if(null == stock || !stock.get车辆零售状态().contains("已卖")){
                continue;
            }
            //如果该si存在那么替换
            SibmbsSettingModel orgModel = sibmbsSettingRepository.findSisettingByVinAndCode(vo.getVin(),permit,vo.getSiTypeCode());
            //si——bmbs——code不存在跳过
            SibmbsSettingModel bmbs = null ==orgModel?new SibmbsSettingModel():orgModel;
            //匹配SI选项
            SisettingModel codeModel = sisettingRepository.findSisettingByCode(vo.getSiTypeCode());
            if(null == codeModel){
                continue;
            }
            bmbs.setVin(stock.get车架号());
            bmbs.setStockId(stock.get库存编号());
            bmbs.setCreatedTime(DateFormatUtils.getFormatDate(vo.getConfirmDate(),DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD));
            bmbs.setValidStartDate(DateFormatUtils.getDateByMonthFirstDay(DateFormatUtils.getFormatDate(vo.getConfirmDate(),DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD)));
            bmbs.setValidEndDate(DateFormatUtils.getDateByMonthLastDay(DateFormatUtils.getFormatDate(vo.getConfirmDate(),DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD)));
            bmbs.setCarTypeId(stock.get车型编号());
            bmbs.setSetType(SelectBoxOptionEnum.SIType.getIndex("车辆"));
            bmbs.setPermit(permit);
            bmbs.setSiBmbsCode(codeModel.getSiTypeCode());
            bmbs.setSiSettingId(codeModel.getId());
            bmbs.setSiAmount(NumberUtils.getBigDecimalValue(vo.getConfirmAmount()));
            bmbs.setpNum(null == bmbs.getId()?pnum:bmbs.getpNum());
            sibmbsSettingRepository.save(bmbs);
            //存入si 汇总 按照许可 指定存入项ID(1,2,3,4,5,6,7,8,11,12,13,14,15,20,21,22,23,25,26,29,30,31,33,34,35) ）
            //if(DefaultValueConstant.getSiInIdList().contains(codeModel.getId())){
                IncomeAdjustmentModel income = isInsertSi("1",stock.get库存编号(),permit,stock.get车型编号());
                inAdjustmentRepository.save(bulidSIbmbsModel(income,bmbs,permit,userName,index));
                index ++;
            //}
        }
        return null;
    }

    @Override
    public PageData getIncomeAdjustmentInfoBySi(GetIncomeAdjustmentByConditionRequest request) {
        return setRepository.getIncomeAdjustmentInfoBySi(request.permit, request.shengchanId, request.customerName,
                request.openTicketDate, request.jibie, request.carModel, request.carVINCode, request.type,
                request.getPageSize(), request.getPageIndex());
    }

    @Override
    public List getIncomeAdjustmentInfoBySiInit(String permit, String id) {
        return setRepository.getIncomeAdjustmentInfoBySiInit(permit,id);
    }

    @Override
    public String saveSiNonVehicle(SiNonVehicle siNonVehicle, String permit, String userName) throws Exception{
        //根据传入对像的SI不为空的构建SI子项集合
        List<SibmbsSettingModel>  list = buildSiNonVehicle(siNonVehicle,permit);
        //是否存在icome表中存在更新不存在新增
        //
        int index =0;
        for (SibmbsSettingModel obj:list) {
            //子项处理
            sibmbsSettingRepository.save(obj);
            //存入si 汇总按照许可指定子选项ID统计
            IncomeAdjustmentModel income =  inAdjustmentRepository.getIncomeAdjustmentByPnum(obj.getpNum(),permit);//isInsertSi(siNonVehicle.setType,null,permit,siNonVehicle.carCode);
           //如果批次没能找到，再查询是否本月有过调整没有才新增 否则替换
            if(null == income){
                income = inAdjustmentRepository.getIncomeAdjustmentByValidDate(permit,obj.getValidStartDate(),obj.getValidEndDate(),siNonVehicle.carCode,siNonVehicle.setType);
            }
            inAdjustmentRepository.save(bulidSIbmbsModel(income,obj,permit,userName,index));
            index ++;
        }

        return null;
    }

    @Override
    public String updateSiNonVehicle(SiNonVehicleUpdate siNonVehicle, String permit, String userName,Integer pNum) throws Exception {
        if(null == pNum){
            return "1";
        }
        //根据传入批次ID查询所有该批次的子项
        List<SibmbsSettingModel>  list = sibmbsSettingRepository.findListByPnum(pNum,permit);
        //取得车型ID，调整类型，调整时间
        String time =null;
        Integer carCode =null;
        String type =null;
        //删除所有之前子项
        for(SibmbsSettingModel obj:list){
            time =DateFormatUtils.getFormatDateToString(obj.getCreatedTime(),DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD);
            carCode = obj.getCarTypeId();
            type = String.valueOf(obj.getSetType());
            sibmbsSettingRepository.delete(obj.getId());
        }
        //再走新增逻辑
        saveSiNonVehicle(getSiNonVehicle(siNonVehicle,carCode,type,time),permit,userName);
     /*   int index =0;
       IncomeAdjustmentModel income = inAdjustmentRepository.getIncomeAdjustmentByPnum(pNum,permit);//isInsertSi(siNonVehicle.setType,null,permit,siNonVehicle.carCode);按照许可指定子选项ID统计
        for (SibmbsSettingModel obj:list) {
            obj=updateSiNonVehicle(obj,siNonVehicle,permit);
            sibmbsSettingRepository.save(obj);
            //根据批次获取总信息更新SI汇总金额
            inAdjustmentRepository.save(bulidSIbmbsModel(income,obj,permit,userName,index));
        }*/
        return null;
    }

    @Override
    public ResultData getOneUserManyAccountList() {
        List reList = this.setRepository.getOneUserManyAccountList();
        if (reList.size() == 0) {
            return new ResultData("true", "暂无记录", null);
        } else {
            return new ResultData("true", null, new PageData(reList, reList.size()));
        }
    }

    @Override
    public ResultData addOneUserManyAccount(AddOneUserManyAccountRequest request) {
        logger.info("addOneUserManyAccount 传入参数为:" + JsonObjectUtils.writeAsJson(request));
        String errMsg = "新增同用户多账号异常";
        try {
            // 邮箱为空
            if (request.userMail == null) return new ResultData("false", "账号不能为空", null);
            // 邮箱为连续空格
            String triUserMail = request.userMail.trim();
            if (triUserMail.length() == 0) return new ResultData("false", "账号不能全是空格", null);

            用户Model userMo = userRepository.findModelByUsername(triUserMail);
            if (userMo == null) return new ResultData("false", "找不到对应的账号", null); // 找不到邮箱
            if (!"总经理".equals(userMo.get角色())) return new ResultData("false", "该用户不是总经理", null);

            // 组名为空
            if (request.approvalGroup == null) return new ResultData("false", "分组名不能为null", null);
            // 组名为连续空格
            String trimApprovalGroup = request.approvalGroup.trim();
            if (trimApprovalGroup.length() == 0) return new ResultData("false", "分组名不能全是空格", null);

            userMo.setApprovalGroup(trimApprovalGroup);
            return new ResultData("true", null, null);
        } catch (Exception e) {
            logger.error(errMsg, e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultData("false", errMsg, null);
        }
    }

    @Override
    public ResultData delOneUserManyAccount(AddOneUserManyAccountRequest request) {
        logger.info("delOneUserManyAccount 传入参数为:" + JsonObjectUtils.writeAsJson(request));
        String errMsg = "删除账号与分组的关系异常";
        try {
            if (request.userMail == null || request.userMail.trim().length() == 0)
                return new ResultData("false", "账号不合法", null);
            用户Model userMo = userRepository.findModelByUsername(request.userMail.trim());
            if (userMo == null) {
                return new ResultData("false", "找不到对应的账号", null);
            } else if (!"总经理".equals(userMo.get角色())) {
                return new ResultData("false", "此账号不是总经理角色", null);
            } else {
                userMo.setApprovalGroup("");
                return new ResultData("true", null, null);
            }
        } catch (Exception e) {
            logger.error(errMsg, e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultData("false", errMsg, null);
        }
    }



    /**
     * 判断SI表中当前记录是否存在
     * @param sitype
     * @param stockCode
     * @param permit
     * @param carCode
     * @return
     */
    private IncomeAdjustmentModel isInsertSi(String sitype,Integer stockCode,String permit,Integer carCode){
        IncomeAdjustmentModel stockCodeModel = null;
        if ("1".equals(sitype) || "车辆".equals(sitype)) {//类型为1  用库存编号去查
            stockCodeModel = inAdjustmentRepository.getIncomeAdjustmentByStockCode(stockCode, permit);
        } else {//其他用 车型编号判断
            stockCodeModel = inAdjustmentRepository.getIncomeAdjustmentByCarCode(carCode, permit, sitype);
        }
        return stockCodeModel;
    }

    /**
     * 更新SI的时候不覆盖原来保存的其他SI率值
     * @param newModel
     * @param orgModel
     * @param reportType
     * @return
     */
    private IncomeAdjustmentModel buildUpdateSiModel(IncomeAdjustmentModel newModel,IncomeAdjustmentModel orgModel,Integer reportType){
        orgModel.setCarCode(newModel.getCarCode());
        orgModel.setStockCode(newModel.getStockCode());
        //其他属性
        orgModel.setLastUpdateUser(newModel.getLastUpdateUser());
        orgModel.setPermit(newModel.getPermit());
        orgModel.setType(newModel.getType());
        orgModel.setLastUpdateDate(newModel.getLastUpdateDate());
        orgModel.setAdjustDate(newModel.getAdjustDate());
        orgModel.setValidStartDate(newModel.getValidStartDate());
        orgModel.setValidEndDate(newModel.getValidEndDate());
        switch (reportType){
            case DefaultValueConstant.REPORT_LIVE_SI_FINANCIAL:
                orgModel.setFinancePoundageAdjust(newModel.getFinancePoundageAdjust());
                orgModel.setFinancePoundageAdjustBefor(newModel.getFinancePoundageAdjustBefor());
                orgModel.setFinancePoundageAdjustReal(newModel.getFinancePoundageAdjustReal());
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_DISCOUNT:
                orgModel.setFinanceSoftLoanAdjust(newModel.getFinanceSoftLoanAdjust());
                orgModel.setFinanceSoftLoanAdjustBefor(newModel.getFinanceSoftLoanAdjustBefor());
                orgModel.setFinanceSoftLoanAdjustReal(newModel.getFinanceSoftLoanAdjustReal());
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_INSURANCE:
                orgModel.setInsurancePoundageAdjust(newModel.getInsurancePoundageAdjust());
                orgModel.setInsurancePoundageAdjustBefor(newModel.getInsurancePoundageAdjustBefor());
                orgModel.setInsurancePoundageAdjustReal(newModel.getInsurancePoundageAdjustReal());
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_MARKET:
            case DefaultValueConstant.REPORT_LIVE_SI_MARKET_GIVE:
            orgModel.setAfterMarketProductCostAdjust(newModel.getAfterMarketProductCostAdjust());
            orgModel.setAfterMarketProductCostAdjustBefor(newModel.getAfterMarketProductCostAdjustBefor());
            orgModel.setAfterMarketProductCostAdjustReal(newModel.getAfterMarketProductCostAdjustReal());
                orgModel.setGive(isGive(reportType));
            case DefaultValueConstant.REPORT_LIVE_SI_FIVE_STAR:
                orgModel.setFiveStarsExtendCostAdjust(newModel.getFiveStarsExtendCostAdjust());
                orgModel.setFiveStarsExtendCostAdjustBefor(newModel.getFiveStarsExtendCostAdjustBefor());
                orgModel.setFiveStarsExtendCostAdjustReal(newModel.getFiveStarsExtendCostAdjustReal());
                orgModel.setGive(isGive(reportType));
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_THREE_SECURE:
                orgModel.setThirdExtendCostAdjust(newModel.getThirdExtendCostAdjust());
                orgModel.setThirdExtendCostAdjustReal(newModel.getThirdExtendCostAdjustReal());
                orgModel.setThirdExtendCostAdjustBefor(newModel.getThirdExtendCostAdjustBefor());
                orgModel.setGive(isGive(reportType));
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_MARKET_BUY:
                orgModel.setAfterMarketProductCostBuyAdjust(newModel.getAfterMarketProductCostBuyAdjust());
                orgModel.setAfterMarketProductCostBuyAdjustBefor(newModel.getAfterMarketProductCostBuyAdjustBefor());
                orgModel.setAfterMarketProductCostBuyAdjustReal(newModel.getAfterMarketProductCostBuyAdjustReal());
                orgModel.setGive(isGive(reportType));
        }
        return  orgModel;
    }

    /**
     * 构建SI原先率值、实际率值和差值
     * @param newModel            break;

     * @param vo
     * @param reportType
     * @param stock
     * @return
     */
    private IncomeAdjustmentModel buildSiModel(IncomeAdjustmentModel newModel,SiImportVo vo,Integer reportType,Lsh库存表Model stock){
        报价单表Model model = null;
        if(null != stock){
           model = getPriceOrder(stock.get报价编号());
        }
        BigDecimal beforValue = new BigDecimal(0.00);
        Boolean isGive = false;
        if(null != model ){
            Map<String,Object> map = getBeforValueByType(reportType,model);
            beforValue = (BigDecimal) map.get("beforValue");
            isGive =(Boolean) map.get("isGive");
        }
        switch (reportType){
            case DefaultValueConstant.REPORT_LIVE_SI_FINANCIAL:
                newModel.setFinancePoundageAdjustBefor(beforValue);//取得之前值
                newModel.setFinancePoundageAdjustReal(NumberUtils.getBigDecimalValue(vo.getFinancialCommissionReceipts()));//保存实际值
                newModel.setFinancePoundageAdjust(AmountUtils.subtract(newModel.getFinancePoundageAdjustReal(),newModel.getFinancePoundageAdjustBefor()==null?new BigDecimal(0.00):newModel.getFinancePoundageAdjustBefor()));//计算差值值
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_DISCOUNT:
                newModel.setFinanceSoftLoanAdjust(beforValue);
                newModel.setFinanceSoftLoanAdjustReal(NumberUtils.getBigDecimalValue(vo.getDiscountAmountReceipts()));
                newModel.setFinanceSoftLoanAdjust(AmountUtils.subtract(newModel.getFinanceSoftLoanAdjustReal(),newModel.getFinanceSoftLoanAdjustBefor() ==null?new BigDecimal(0.00):newModel.getFinanceSoftLoanAdjustBefor()));
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_INSURANCE:
                newModel.setInsurancePoundageAdjustBefor(beforValue);
                newModel.setInsurancePoundageAdjustReal(NumberUtils.getBigDecimalValue(vo.getInsuranceReceipts()));
                newModel.setInsurancePoundageAdjust(AmountUtils.subtract(newModel.getInsurancePoundageAdjustReal(),newModel.getInsurancePoundageAdjustBefor() ==null?new BigDecimal(0.00):newModel.getInsurancePoundageAdjustBefor()));
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_MARKET:
            case DefaultValueConstant.REPORT_LIVE_SI_MARKET_GIVE:
                newModel.setGive(true);
                newModel.setAfterMarketProductCostAdjustBefor(beforValue);
                newModel.setAfterMarketProductCostAdjustReal(NumberUtils.getBigDecimalValue(vo.getMarketReceipts()));
                newModel.setAfterMarketProductCostAdjust(AmountUtils.subtract(newModel.getAfterMarketProductCostAdjustReal(),newModel.getAfterMarketProductCostAdjustBefor() ==null?new BigDecimal(0.00):newModel.getAfterMarketProductCostAdjustBefor()));
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_FIVE_STAR:
                newModel.setGive(isGive);
                newModel.setFiveStarsExtendCostAdjustBefor(beforValue);
                newModel.setFiveStarsExtendCostAdjustReal(NumberUtils.getBigDecimalValue(vo.getFiveStarReceipts()));
                newModel.setFiveStarsExtendCostAdjust(AmountUtils.subtract(newModel.getFiveStarsExtendCostAdjustReal(),newModel.getFiveStarsExtendCostAdjustBefor() ==null?new BigDecimal(0.00):newModel.getFiveStarsExtendCostAdjustBefor()));
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_THREE_SECURE:
                newModel.setGive(isGive);
                newModel.setThirdExtendCostAdjustBefor(beforValue);
                newModel.setThirdExtendCostAdjustReal(NumberUtils.getBigDecimalValue(vo.getThirdReceipts()));
                newModel.setThirdExtendCostAdjust(AmountUtils.subtract(newModel.getThirdExtendCostAdjustReal(),newModel.getThirdExtendCostAdjustBefor() ==null?new BigDecimal(0.00):newModel.getThirdExtendCostAdjustBefor()));
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_MARKET_BUY:
                newModel.setGive(false);
                newModel.setAfterMarketProductCostBuyAdjustBefor(beforValue);
                newModel.setAfterMarketProductCostBuyAdjustReal(NumberUtils.getBigDecimalValue(vo.getMarketReceipts()));
                newModel.setAfterMarketProductCostBuyAdjust(AmountUtils.subtract(newModel.getAfterMarketProductCostBuyAdjustReal(),newModel.getAfterMarketProductCostBuyAdjustBefor() ==null?new BigDecimal(0.00):newModel.getAfterMarketProductCostBuyAdjustBefor()));
                break;
        }
        return  newModel;
    }

    /**
     * 验证导入SIbmbs项数据是否有效
     * @param vo
     * @return
     */
    private boolean validSibmbs(SibmbsImportVo vo){
        boolean re = false;
        if(null == vo){
            return re;
        }
        if("已通过".contains(vo.getCheckResult()) && !StringUtils.isNullOrBlank(vo.getVin())){
            re =true;
        }
        return  re;
    }

    /**
     * 根据TYPE获取之前值
     * @param reportType
     * @param model
     * @return
     */
    private Map<String,Object> getBeforValueByType(Integer reportType,报价单表Model model){
        Map<String,Object> result =  Maps.newHashMap();
        BigDecimal beforValue = new BigDecimal(0.00);
        Boolean isGive = false;
        if(null == model){
            result.put("beforValue",null ==beforValue?new BigDecimal(0.00):beforValue);
            result.put("isGive",isGive);
            return result;
        }
        switch (reportType){
            case DefaultValueConstant.REPORT_LIVE_SI_FINANCIAL://金融手续费——>（金融手续费）报价金融表
                if(null != model.get金融()){
                    报价金融表Model finance =报价金融表Repository.getLatestfinalMsgs(model.get金融()); //查询报价金融信息
                    if(null != finance){
                        beforValue = StringUtils.isNullOrBlank(finance.get金融手续费())?beforValue:new BigDecimal(Double.parseDouble(finance.get金融手续费()));
                    }
                }
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_DISCOUNT://贴息应收——>（贴息金额）lsh金融申请附属
                if(!StringUtils.isNullOrBlank(model.get初始报价单号())){
                    Lsh金融申请附属Model finance =lsh金融申请附属Repository.getFinanceApplyRelyModel(model.get初始报价单号()); //查询报价金融信息
                    if(null != finance){
                        beforValue = StringUtils.isNullOrBlank(finance.get贴息金额())?beforValue:finance.get贴息金额();
                    }
                }
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_INSURANCE://保险手续费应收——>（交强险手续费 + 商业险手续费）报价保险表
                if(null != model.get保险编号()){
                    报价保险表Model finance =报价保险表Repository.findby编号(model.get保险编号());
                    if(null != finance && (null != finance.get交强险手续费() || null != finance.get商业险手续费()) ){
                        beforValue = AmountUtils.add(StringUtils.isNullOrBlank(finance.get交强险手续费())?new BigDecimal(0.00):new BigDecimal(Double.parseDouble(finance.get交强险手续费())),
                                StringUtils.isNullOrBlank(finance.get商业险手续费())?new BigDecimal(0.00):new BigDecimal(Double.parseDouble(finance.get商业险手续费())));
                    }
                }
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_MARKET_GIVE:  //后市场预计成本（赠送）——>（精品成本）报价精品详细表 where折扣价为0 sum(成本)
                if(null != model.get精品()){
                    BigDecimal finance =报价精品详细表Repository.findAfterIsFree(model.get精品());
                    if(null != finance){
                        beforValue = StringUtils.isNullOrBlank(finance)?beforValue:finance;
                        isGive =  finance.doubleValue() <= 0.00 ?true:false;
                    }
                }
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_MARKET_BUY: //后市场预计成本（非赠送）——>（精品成本）报价精品详细表 where折扣价大于0 sum(成本)
                if(null != model.get精品()){
                    BigDecimal finance =报价精品详细表Repository.findAfterBuy(model.get精品());
                    if(null != finance){
                        beforValue = StringUtils.isNullOrBlank(finance)?beforValue:finance;
                        isGive =  finance.doubleValue() <= 0.00 ?true:false;
                    }
                }
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_FIVE_STAR://五星延保预估成本——>（延保原价）报价五星延保
            case DefaultValueConstant.REPORT_LIVE_SI_THREE_SECURE:
                if(DefaultValueConstant.REPORT_LIVE_SI_THREE_SECURE == reportType && null != model.get延保编号()){
                    报价五星延保Model yanbao =报价五星延保Repository.findby编号(model.get延保编号());
                    if(null != yanbao){
                        beforValue = StringUtils.isNullOrBlank(yanbao.getThirdMsrp())?beforValue:new BigDecimal(Double.parseDouble(yanbao.getThirdMsrp()));
                        isGive =  Double.parseDouble(yanbao.getThirdMsrp()) <= 0.00 ?true:false;
                    }
                }else if (DefaultValueConstant.REPORT_LIVE_SI_FIVE_STAR == reportType && null != model.get延保编号()){
                    报价五星延保Model yanbao =报价五星延保Repository.findby编号(model.get延保编号());
                    if(null != yanbao) {
                        beforValue = StringUtils.isNullOrBlank(yanbao.getManufactorMsrp()) ? beforValue : new BigDecimal(Double.parseDouble(yanbao.getManufactorMsrp()));
                        isGive = Double.parseDouble(yanbao.getManufactorMsrp()) <= 0.00 ? true : false;
                    }
                }
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_BMBS://SI应收——>（SUM(随车成本)）报价随车 7项随车 +贴息
                if(null != model.get报价编号()){
                    BigDecimal finance =报价随车表Repository.findby报价编号(model.get报价编号());
                    if(null != finance){
                        beforValue = StringUtils.isNullOrBlank(finance)?beforValue:finance;
                    }
                }
                if(!StringUtils.isNullOrBlank(model.get初始报价单号())){
                    Lsh金融申请附属Model finance =lsh金融申请附属Repository.getFinanceApplyRelyModel(model.get初始报价单号()); //查询报价金融信息
                    if(null != finance){
                        BigDecimal financebeforValue = StringUtils.isNullOrBlank(finance.get贴息金额())?beforValue:finance.get贴息金额();
                        beforValue = AmountUtils.add(beforValue,financebeforValue);
                    }
                }
                break;
        }
        result.put("beforValue",null ==beforValue?new BigDecimal(0.00):beforValue);
        result.put("isGive",isGive);
        return  result ;
    }

    /**
     * bmbs保存\更新Si总项
     * @param income
     * @param bmbs
     * @param permit
     * @return
     */
    private IncomeAdjustmentModel bulidSIbmbsModel( IncomeAdjustmentModel income,SibmbsSettingModel bmbs,String permit,String userName,Integer index) throws Exception{
        IncomeAdjustmentModel buildModel =null;
        if (null == income){
            Map<String,Object> map = getBeforValueByType(DefaultValueConstant.REPORT_LIVE_SI_BMBS,getPriceOrder(getPriceOrderIdByStockId(bmbs.getStockId())));
            BigDecimal beforValue = (BigDecimal) map.get("beforValue");
            Boolean isGive = (Boolean) map.get("isGive");
            buildModel = new IncomeAdjustmentModel();
            buildModel.setGive( isGive);
            buildModel.setCarCode(bmbs.getCarTypeId());
            buildModel.setSiAdjustReal(bmbs.getSiAmount());
            buildModel.setSiAdjustBefor(beforValue);
            buildModel.setSiAdjust(AmountUtils.subtract(buildModel.getSiAdjustReal(),buildModel.getSiAdjustBefor()));//差值 = 原先实际值 - 之前值
            buildModel.setPermit(permit);
            buildModel.setLastUpdateDate(new java.sql.Date(new Date().getTime()));
            buildModel.setAdjustDate(DateFormatUtils.parseStrToSqlDate(bmbs.getCreatedTime()));
            buildModel.setLastUpdateUser(userName);
            buildModel.setType(bmbs.getSetType().toString());
            buildModel.setStockCode(bmbs.getStockId());
            buildModel.setpNum(bmbs.getpNum());
            buildModel.setValidStartDate(DateFormatUtils.parseStrToSqlDate(bmbs.getValidStartDate()));
            buildModel.setValidEndDate(DateFormatUtils.parseStrToSqlDate(bmbs.getValidEndDate()));
        }else{
            buildModel = income;
            buildModel.setLastUpdateDate(new java.sql.Date(new Date().getTime()));
            if(index >0){
                buildModel.setSiAdjustReal(AmountUtils.add(buildModel.getSiAdjustReal(),bmbs.getSiAmount()));//实际值 = 原先实际值 + 当前实际值
            }else{
                buildModel.setSiAdjustReal(bmbs.getSiAmount());//第一次遍历时重置原先主表总值
            }
            //差值 = （当前实际值） - 之前值）
            if(null != buildModel.getSiAdjustBefor()){
                buildModel.setSiAdjust(AmountUtils.subtract(buildModel.getSiAdjustReal(),buildModel.getSiAdjustBefor()));
            }else{
                buildModel.setSiAdjust(buildModel.getSiAdjustReal());
                buildModel.setSiAdjustBefor(new BigDecimal(0.00));
            }
            buildModel.setType(bmbs.getSetType().toString());
            buildModel.setpNum(bmbs.getpNum());
            buildModel.setValidStartDate(DateFormatUtils.parseStrToSqlDate(bmbs.getValidStartDate()));
            buildModel.setValidEndDate(DateFormatUtils.parseStrToSqlDate(bmbs.getValidEndDate()));
            buildModel.setAdjustDate(DateFormatUtils.parseStrToSqlDate(bmbs.getCreatedTime()));
        }
        return buildModel;
    }

    /**
     * 根据报价单D查询报价单信息
     * @param priceNum
     * @return
     */
    private 报价单表Model getPriceOrder(Integer priceNum){
        //根据库存ID查询对应报价单信息
        报价单表Model model =null;
        if(null == priceNum){
            return model;
        }
        return 报价单表Repository.findBy报价编号(priceNum);
    }

    /**
     * 根据报价单D查询报价单信息
     * @param stockId
     * @return
     */
    private Integer getPriceOrderIdByStockId(Integer stockId){
        //根据库存ID查询对应报价单信息
        Lsh库存表Model  model =null;
        if(null == stockId){
            return null;
        }
        return lsh库存表Repository.findOne(stockId).get报价编号();
    }

    /**
     * 除SI 非车辆调整赋值
     * @param orgModel
     * @param siType
     * @param permit
     * @param userName
     * @return
     * @throws Exception
     */
    private  IncomeAdjustmentModel buildOtherNonVehicle(IncomeAdjustmentModel orgModel,Integer siType,String permit,String userName) throws Exception{
        IncomeAdjustmentModel model = orgModel;
        Lsh库存表Model stock =null;
        if("1".equals(orgModel.getType())){
            Integer stock_code = orgModel.getStockCode();
            //2根据生产号查询库存ID、车型ID
            stock = lsh库存表Repository.findLshStockByStockId(stock_code);
            model.setCarCode(null == stock?null:stock.get车型编号());
            model.setStockCode(null == stock?null:stock.get库存编号());
        }else{
            model.setCarCode(orgModel.getCarCode());
        }
        //其他属性
        model.setLastUpdateUser(userName);
        model.setPermit(permit);
        model.setType(orgModel.getType());
        model.setLastUpdateDate(DateFormatUtils.parseStrToSqlDate(new Date()));
        model.setAdjustDate(orgModel.getAdjustDate());
        //构建率值
        SiImportVo vo = new SiImportVo();
        vo.setFiveStarReceipts(String.valueOf(orgModel.getFiveStarsExtendCostAdjust()));
        vo.setThirdReceipts(String.valueOf(orgModel.getThirdExtendCostAdjust()));
        vo.setInsuranceReceipts(String.valueOf(orgModel.getInsurancePoundageAdjust()));
        vo.setFinancialCommissionReceipts(String.valueOf(orgModel.getFinancePoundageAdjust()));
        vo.setDiscountAmountReceipts(String.valueOf(orgModel.getFinanceSoftLoanAdjust()));
        vo.setMarketReceipts(DefaultValueConstant.REPORT_LIVE_SI_MARKET_BUY == siType?String.valueOf(orgModel.getAfterMarketProductCostBuyAdjust()):String.valueOf(orgModel.getAfterMarketProductCostAdjust()));
        model = buildSiModel(model,vo,siType, stock);
        return model;
    }

    /**
     * 构造Si非车辆新增或者编辑子项列表
     * @param siNonVehicle
     * @return
     */
    private List<SibmbsSettingModel> buildSiNonVehicle(SiNonVehicle siNonVehicle,String permit) throws Exception{
        List<SibmbsSettingModel> list = new ArrayList<SibmbsSettingModel>();
        Integer pnum = getMaxPnum();
        if(!StringUtils.isNullOrBlank(siNonVehicle.W)){
            SibmbsSettingModel bmbs= getBySiNonVehicle(siNonVehicle,permit,siNonVehicle.W,"W");
            if(null != bmbs.getSiSettingId()){
                bmbs.setSiAmount(siNonVehicle.W);
                bmbs.setpNum(bmbs.getInsertOrUpdate() ==1?pnum:bmbs.getpNum());
                list.add(bmbs);   //批售
            }
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.R)){
            SibmbsSettingModel bmbs= getBySiNonVehicle(siNonVehicle,permit,siNonVehicle.R,"R");
            if(null != bmbs.getSiSettingId()) {
                bmbs.setSiAmount(siNonVehicle.R);
                bmbs.setpNum(bmbs.getInsertOrUpdate() ==1?pnum:bmbs.getpNum());
                list.add(bmbs);  //零售
            }
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.I)){
            SibmbsSettingModel bmbs= getBySiNonVehicle(siNonVehicle,permit,siNonVehicle.I,"I");
            if(null != bmbs.getSiSettingId()) {
                bmbs.setSiAmount(siNonVehicle.I);
                bmbs.setpNum(bmbs.getInsertOrUpdate() ==1?pnum:bmbs.getpNum());
                list.add(bmbs);//保险
            }
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.PT)){
            SibmbsSettingModel bmbs= getBySiNonVehicle(siNonVehicle,permit,siNonVehicle.PT,"PT");
            if(null != bmbs.getSiSettingId()) {
                bmbs.setSiAmount(siNonVehicle.PT);
                bmbs.setpNum(bmbs.getInsertOrUpdate() ==1?pnum:bmbs.getpNum());
                list.add(bmbs);//购置税
            }
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.SSSC)){
            SibmbsSettingModel bmbs= getBySiNonVehicle(siNonVehicle,permit,siNonVehicle.SSSC,"SSSC");
            if(null != bmbs.getSiSettingId()) {
                bmbs.setSiAmount(siNonVehicle.SSSC);
                bmbs.setpNum(bmbs.getInsertOrUpdate() ==1?pnum:bmbs.getpNum());
                list.add(bmbs);//SSSC
            }
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.RT)){
            SibmbsSettingModel bmbs= getBySiNonVehicle(siNonVehicle,permit,siNonVehicle.RT,"RT");
            if(null != bmbs.getSiSettingId()) {
                bmbs.setSiAmount(siNonVehicle.RT);
                bmbs.setpNum(bmbs.getInsertOrUpdate() ==1?pnum:bmbs.getpNum());
                list.add(bmbs);//旅游礼包
            }
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.SD)){
            SibmbsSettingModel bmbs= getBySiNonVehicle(siNonVehicle,permit,siNonVehicle.SD,"SD");
            if(null != bmbs.getSiSettingId()) {
                bmbs.setSiAmount(siNonVehicle.SD);
                bmbs.setpNum(bmbs.getInsertOrUpdate() ==1?pnum:bmbs.getpNum());
                list.add(bmbs);//SD
            }
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.FV)){
            SibmbsSettingModel bmbs= getBySiNonVehicle(siNonVehicle,permit,siNonVehicle.FV,"FV");
            if(null != bmbs.getSiSettingId()) {
                bmbs.setSiAmount(siNonVehicle.FV);
                bmbs.setpNum(bmbs.getInsertOrUpdate() ==1?pnum:bmbs.getpNum());
                list.add(bmbs);//加油卡
            }
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.CG)){
            SibmbsSettingModel bmbs= getBySiNonVehicle(siNonVehicle,permit,siNonVehicle.CG,"CG");
            if(null != bmbs.getSiSettingId()) {
                bmbs.setSiAmount(siNonVehicle.CG);
                bmbs.setpNum(bmbs.getInsertOrUpdate() ==1?pnum:bmbs.getpNum());
                list.add(bmbs);//实物礼品
            }
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.SC)){
            SibmbsSettingModel bmbs= getBySiNonVehicle(siNonVehicle,permit,siNonVehicle.SC,"SC");
            if(null != bmbs.getSiSettingId()) {
                bmbs.setSiAmount(siNonVehicle.SC);
                bmbs.setpNum(bmbs.getInsertOrUpdate() ==1?pnum:bmbs.getpNum());
                list.add(bmbs);//服务礼券
            }
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.F)){
            SibmbsSettingModel bmbs= getBySiNonVehicle(siNonVehicle,permit,siNonVehicle.F,"F");
            if(null != bmbs.getSiSettingId()) {
                bmbs.setSiAmount(siNonVehicle.F);
                bmbs.setpNum(bmbs.getInsertOrUpdate() ==1?pnum:bmbs.getpNum());
                list.add(bmbs);//金融贴息
            }
        }
        return list;
    }

    /**
     * 构建SI子项
     * @param siNonVehicle
     * @param permit
     * @param amount
     * @param siCode
     * @return
     */
    private SibmbsSettingModel getBySiNonVehicle(SiNonVehicle siNonVehicle,String permit,BigDecimal amount,String siCode) throws Exception{
        //父级是否存在相同月份 存在找到当前项更改值和时间 否则新增
        Date validStart = DateFormatUtils.getDateByMonthFirstDay(DateFormatUtils.getFormatDate(siNonVehicle.setTime,DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD));
        Date validEnd = DateFormatUtils.getDateByMonthLastDay(DateFormatUtils.getFormatDate(siNonVehicle.setTime,DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD));
        IncomeAdjustmentModel income = inAdjustmentRepository.getIncomeAdjustmentByValidDate(permit,validStart,validEnd,siNonVehicle.carCode,siNonVehicle.setType);
        SibmbsSettingModel orgModel =null;
        if(null != income){
            orgModel = sibmbsSettingRepository.findSisettingBypNumAndSiCode(income.getpNum(),permit,siCode,validStart,validEnd,siNonVehicle.carCode,Integer.parseInt(siNonVehicle.setType));
        }
        //si——bmbs——code不存在跳过
        SibmbsSettingModel bmbs = null ==orgModel?new SibmbsSettingModel():orgModel;
        if(null == orgModel){
            //匹配SI选项
            SisettingModel codeModel = sisettingRepository.findSisettingByCode(siCode);
            if(null != codeModel){
                bmbs.setSiSettingId(codeModel.getId());
            }
            bmbs.setPermit(permit);
            bmbs.setCarTypeId(siNonVehicle.carCode);
            bmbs.setSetType(Integer.parseInt(siNonVehicle.setType));
            bmbs.setCreatedTime(DateFormatUtils.getFormatDate(siNonVehicle.setTime,DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD));
            bmbs.setValidStartDate(validStart);
            bmbs.setValidEndDate(validEnd);
            bmbs.setSiBmbsCode(siCode);
            bmbs.setInsertOrUpdate(1);
        }else{
            bmbs.setCreatedTime(DateFormatUtils.getFormatDate(siNonVehicle.setTime,DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD));
            bmbs.setInsertOrUpdate(2);
        }
        return bmbs;
    }

    /**
     * 获取批次
     * @return
     */
    private Integer getMaxPnum(){
        //查询上次最大批次
        Integer maxpNum = sibmbsSettingRepository.findMaxPnum();
        return null == maxpNum?1:maxpNum+1;
    }


    /**
     * 构造Si非车辆编辑子项列表
     * @param siNonVehicle
     * @return
     */
    private SibmbsSettingModel updateSiNonVehicle(SibmbsSettingModel org,SiNonVehicleUpdate siNonVehicle,String permit){
        if(!StringUtils.isNullOrBlank(siNonVehicle.W) && org.getSiBmbsCode().equals("W")){
            org.setSiAmount(siNonVehicle.W);
            return org;   //批售
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.R) && org.getSiBmbsCode().equals("R")){
            org.setSiAmount(siNonVehicle.R);
                return org;  //零售
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.I) && org.getSiBmbsCode().equals("I")){
            org.setSiAmount(siNonVehicle.I);
            return org;//保险
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.PT) && org.getSiBmbsCode().equals("PT")){
            org.setSiAmount(siNonVehicle.PT);
            return org;//购置税
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.SSSC)&& org.getSiBmbsCode().equals("SSSC")){
            org.setSiAmount(siNonVehicle.SSSC);
            return org;//SSSC
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.RT) && org.getSiBmbsCode().equals("RT")){
            org.setSiAmount(siNonVehicle.RT);
            return org;//旅游礼包
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.SD) && org.getSiBmbsCode().equals("SD")){
            org.setSiAmount(siNonVehicle.SD);
            return org;//SD
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.FV) && org.getSiBmbsCode().equals("FV")){
            org.setSiAmount(siNonVehicle.FV);
            return org;//加油卡
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.CG) && org.getSiBmbsCode().equals("CG")){
            org.setSiAmount(siNonVehicle.CG);
            return org;//实物礼品
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.SC) && org.getSiBmbsCode().equals("SC")){
            org.setSiAmount(siNonVehicle.SC);
            return org;//服务礼券
        }
        if(!StringUtils.isNullOrBlank(siNonVehicle.F) && org.getSiBmbsCode().equals("F")){
            org.setSiAmount(siNonVehicle.F);
            return org;//金融贴息
        }
        return null;
    }

    /**
     * 是否赠送
     * @param siType
     * @return
     */
    private boolean isGive(Integer siType){
        boolean re  = false;
        switch (siType){
            case DefaultValueConstant.REPORT_LIVE_SI_MARKET_GIVE:
                re = true;
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_MARKET_BUY:
                re = false;
                break;
        }
        return re;
    }

    /**
     * 根据入口置空相应SI值
     * @param siType
     * @param org
     * @return
     */
    private IncomeAdjustmentModel deleteBySiType(Integer siType,IncomeAdjustmentModel org){
        switch (siType){
            case DefaultValueConstant.REPORT_LIVE_SI_BMBS:
                org.setSiAdjust(null);
                org.setSiAdjustReal(null);
                org.setSiAdjustBefor(null);
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_INSURANCE:
                org.setInsurancePoundageAdjust(null);
                org.setInsurancePoundageAdjustBefor(null);
                org.setInsurancePoundageAdjustReal(null);
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_FINANCIAL:
                org.setFinancePoundageAdjust(null);
                org.setFinancePoundageAdjustBefor(null);
                org.setFinancePoundageAdjustReal(null);
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_FIVE_STAR:
                org.setFiveStarsExtendCostAdjust(null);
                org.setFiveStarsExtendCostAdjustBefor(null);
                org.setFiveStarsExtendCostAdjustReal(null);
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_MARKET_GIVE:
                org.setAfterMarketProductCostAdjust(null);
                org.setAfterMarketProductCostAdjustBefor(null);
                org.setAfterMarketProductCostAdjustReal(null);
                break;
            case DefaultValueConstant.REPORT_LIVE_SI_MARKET_BUY:
                org.setAfterMarketProductCostBuyAdjust(null);
                org.setAfterMarketProductCostBuyAdjustBefor(null);
                org.setAfterMarketProductCostBuyAdjustReal(null);
                break;
        }
        return  org;
    }


    @Override
    @Transactional
    public boolean sendFinancingInfo(SendInsInfo sendInsInfo,String permit,String userName){
        boolean flag = false;
        try {
            //判断性别
            String call;
            String salesCode  = sendInsInfo.salesCode;
            String phone = sendInsInfo.teleNumber;
            String sex =  顾客记录汇总Repository.findCusByCustomerIDAndPhone(salesCode,phone);
            if("男".equals(sex)){
                call="先生";
            }else if ("女".equals(sex)){
                call="女士";
            }else {
                call="先生/女士";
            }

            if ("新车出入账".equals(sendInsInfo.state)) {
                String news = "客户:" + sendInsInfo.cusName + call+"，电话号码:" + sendInsInfo.teleNumber + "，财务新车出入账完成，请跟进";
                //极光推送
                JsonObject json = JsonObjectUtils.getJsonObject("财务", null, null, sendInsInfo.teleNumber, null, sendInsInfo.salesCode);
                List sendName = Lists.newArrayList();
                sendName.add(sendInsInfo.salesCode);
                JPush.SendPushITaskForAndroidAndIos(news, news, json, sendName);
                //存入lsh数据库
                LshMsgUtils.getLshMsg(permit, userName, permit, sendInsInfo.salesCode, "财务", news,
                        userName, sendInsInfo.teleNumber);
            }
            if ("新车开票".equals(sendInsInfo.state)) {
                String news = "客户:" + sendInsInfo.cusName + call+"，电话号码:" + sendInsInfo.teleNumber + "，财务新车开票完成，请跟进";
                //极光推送
                JsonObject json = JsonObjectUtils.getJsonObject("财务", null, null, sendInsInfo.teleNumber, null, sendInsInfo.salesCode);
                List sendName = Lists.newArrayList();
                sendName.add(sendInsInfo.salesCode);
                JPush.SendPushITaskForAndroidAndIos(news, news, json, sendName);
                //存入lsh数据库
                LshMsgUtils.getLshMsg(permit, userName, permit, sendInsInfo.salesCode, "财务", news,
                        userName, sendInsInfo.teleNumber);
            } else if ("退票".equals(sendInsInfo.state)) {
                String news = "客户:" + sendInsInfo.cusName + call+"，电话号码:" + sendInsInfo.teleNumber + "，财务退票完成，请查看。";
                //极光推送
                JsonObject json = JsonObjectUtils.getJsonObject("财务", null, null, sendInsInfo.teleNumber, null, sendInsInfo.salesCode);
                List sendName = Lists.newArrayList();
                sendName.add(sendInsInfo.salesCode);
                JPush.SendPushITaskForAndroidAndIos(news, news, json, sendName);
                //存入lsh数据库
                LshMsgUtils.getLshMsg(permit, userName, permit, sendInsInfo.salesCode, "财务", news,
                        userName, sendInsInfo.teleNumber);
            } else if ("换票".equals(sendInsInfo.state)) {
                String news = "客户:" + sendInsInfo.cusName + call+"，电话号码:" + sendInsInfo.teleNumber + "，财务换票完成，请查看。";
                //极光推送
                JsonObject json = JsonObjectUtils.getJsonObject("财务", null, null, sendInsInfo.teleNumber, null, sendInsInfo.salesCode);
                List sendName = Lists.newArrayList();
                sendName.add(sendInsInfo.salesCode);
                JPush.SendPushITaskForAndroidAndIos(news, news, json, sendName);
                //存入lsh数据库
                LshMsgUtils.getLshMsg(permit, userName, permit, sendInsInfo.salesCode, "财务", news,
                        userName, sendInsInfo.teleNumber);
            }
            flag = true;

        } catch (Exception e) {
            logger.error("财务消息发送异常", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }
        return flag;

    }

    /**
     * 判断审批名是具体账号，还是角色
     * @param userName 审批名
     * @return true为账号, false为角色
     */
    @Override
    public boolean isRoleName(String userName){
        Map roleName=setRepository.getAllLshRoleName();
        if (userName.contains("_")) { // 角色审批
            return !roleName.containsKey(userName.split("_")[1]);
        } else { // 账号审批
            return true;
        }
    }

    /**
     * 请求体转化
     * @param siNonVehicle
     * @param carCode
     * @param type
     * @param time
     * @return
     */
    private SiNonVehicle  getSiNonVehicle(SiNonVehicleUpdate siNonVehicle,Integer carCode,String type,String time){
        SiNonVehicle si  = new  SiNonVehicle();
        si.carCode = carCode;
        si.setTime = time;
        si.setType = type;
        si.CG = siNonVehicle.CG;
        si.F = siNonVehicle.F;
        si.FV = siNonVehicle.FV;
        si.I = siNonVehicle.I;
        si.PT = siNonVehicle.PT;
        si.R = siNonVehicle.R;
        si.RT = siNonVehicle.RT;
        si.SC = siNonVehicle.SC;
        si.SD = siNonVehicle.SD;
        si.SSSC =siNonVehicle.SSSC;
        si.W = siNonVehicle.W;
        return si;
    }

    /**
     * 根据生产号获取采购经销商和调车协商款项金额的状态
     *
     * @param proId
     * @return
     */
    @Override
    public ResultData getDealerByProId(String proId) {
        Map map = new HashMap();
        List list = new ArrayList();
        try {
            //采购经销商状态 0：不可编辑；1：可编辑
            String buyDealerStatus = "0";
            //协商调车款项金额状态:0 不可编辑；1:可编辑
            String arrangedMoneyStatus = "0";
            if ("".equals(proId) || proId == null) {
                return new ResultData("false", "传入的生产号有误，生产号：" + proId);
            }
            //根据生产号查询库存信息
            Lsh库存表Model lshRecord = lsh库存表Repository.findLshRecordByProId(proId);
            if (lshRecord == null) {
                return new ResultData("false", "没有此生产号的库存信息，生产号：" + proId);
            }

            //1、批发日期如果为空，不允许修改采购经销商；
            if (lshRecord.get批发日期() != null && !"".equals(lshRecord.get批发日期())) {

                //2、调车的车辆(live系统调车的情况)不允许修改采购经销商和调车协商价（含税），即调车日志表有此库存信息(type=0)；
                List<CarTransferLogModel> logLiveList = carTransferLogRepository.findByStoreIdAndType(lshRecord.get库存编号(), 0);
                if (logLiveList.size() == 0 || logLiveList == null) {
                    buyDealerStatus = "1";
                    arrangedMoneyStatus = "1";
                }
            }
            map.put("buyDealerStatus", buyDealerStatus);
            map.put("arrangedMoneyStatus", arrangedMoneyStatus);
            list.add(map);

        } catch (Exception e) {
            logger.error("查询异常", e);
            return new ResultData("false", "查询异常");
        }
        return new ResultData("true", "查询采购批发商和调车协商款项金额状态", new PageData(list, list.size()));
    }

    /**
     * 获取非live的经销商
     *
     * @return
     */
    @Override
    public ResultData getAllNotLiveDealers() {
        List dealerList = new ArrayList();
        try {
            dealerList = setRepository.getAllNotLiveDealers();
        } catch (Exception e) {
            logger.error("查询失败", e);
            return new ResultData("false", "查询非live经销商失败");
        }
        return new ResultData("true", "查询非live经销商成功", new PageData(dealerList, dealerList.size()));
    }

    /**
     * 获得经销商设置的sc线索跟进周期
     * @return
     */
    @Override
    public ResultData getBasicForScFollowTime(HttpServletRequest req) {
        List modelList = new ArrayList<>();
        try {
            String permit = SessionInterceptor.getLicense(req);
            Map map=new LinkedHashMap();
            Itask基础设置Model model1 = this.itask基础设置Repository.finByPermitAndName(permit, "A级线索跟进周期");
            Itask基础设置Model model2 = this.itask基础设置Repository.finByPermitAndName(permit, "B级线索跟进周期");
            Itask基础设置Model model3 = this.itask基础设置Repository.finByPermitAndName(permit, "C级线索跟进周期");
            Itask基础设置Model model4 = this.itask基础设置Repository.finByPermitAndName(permit, "D级线索跟进周期");
            if (model1 != null) {
                map.put("A级线索跟进周期",model1.get值());
            }
            if (model2 != null) {
                map.put("B级线索跟进周期",model2.get值());
            }
            if (model3 != null) {
                map.put("C级线索跟进周期",model3.get值());
            }
            if (model4 != null) {
                map.put("D级线索跟进周期",model4.get值());
            }
            if (map.size() == 0) {
                map.put("A级线索跟进周期",0);
                map.put("B级线索跟进周期",0);
                map.put("C级线索跟进周期",0);
                map.put("D级线索跟进周期",0);
                modelList.add(map);
                return new ResultData("false", "该经销商未设置线索跟进周期",new PageData(modelList, modelList.size()));
            } else {
                modelList.add(map);
                return new ResultData("true", "查询经销商线索跟进周期成功", new PageData(modelList, modelList.size()));
            }
        } catch (Exception e) {
            logger.error("查询失败", e);
            return new ResultData("false", "查询经销商线索跟进周期失败");
        }
    }

    /**
     * 经销商设置sc线索跟进周期
     * @param map
     * @return
     */
    @Override
    @Transactional
    public ResultData saveBasicForScFollowTime(HttpServletRequest request,Map map) {
        try {
            Timestamp nowtime = new Timestamp(new Date().getTime());
            String permit = SessionInterceptor.getLicense(request);
            String username=SessionInterceptor.getUsername(request);
            String aClass = (String) map.get("A级线索跟进周期");
            String bClass = (String) map.get("B级线索跟进周期");
            String cClass = (String) map.get("C级线索跟进周期");
            String dClass = (String) map.get("D级线索跟进周期");
            String[] strarr2={"A级线索跟进周期","B级线索跟进周期","C级线索跟进周期","D级线索跟进周期"};
            String[] strarr = new String[]{aClass, bClass, cClass, dClass};
            for (int i = 0; i < strarr.length; i++) {
                if (Strings.isNullOrEmpty(strarr[i])) {
                    continue;
                }
                Itask基础设置Model model =new Itask基础设置Model();
                model=this.itask基础设置Repository.finByPermitAndName(permit, strarr2[i]);
                if (model == null) {//为空,添加
                    Itask基础设置Model m=new Itask基础设置Model();
                    m.set许可(permit);
                    m.set设置项目(strarr2[i]);
                    m.set值(strarr[i]);
                    m.set更新账号(username);
                    m.set更新时间(nowtime);
                    itask基础设置Repository.save(m);
                } else {//不为空 修改
                    itask基础设置Repository.updByPermitAndName(permit, strarr2[i], strarr[i], nowtime, username);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("保存经销商设置线索跟进周期失败", e);
            return new ResultData("false","保存经销商设置线索跟进周期失败");
        }
        return new ResultData("true","设置线索跟进周期成功");
    }


    @Override
    public ResultData saveClueChannel(List<Itask基础设置Model> itaskDataModel) {
        if (null != itaskDataModel && !itaskDataModel.isEmpty()) {
            for (Itask基础设置Model itaskModel : itaskDataModel) {
                String itemName = itaskModel.get设置项目().trim();
                String valueStr  = itaskModel.get值();
                if (!StringUtils.isNullOrBlank(itaskModel.get值())) {
                    // 参数是否为数字
                    if (!org.apache.commons.lang3.StringUtils.isNumeric(valueStr)) {
                        return new ResultData("false","月份输入不合法,输入范围：1-12",null);
                    }
                    // 参数输入范围校验 1-12
                    if ("邀约交车客户规则".equals(itemName) || "在购名单导出日期1".equals(itemName) || "在购名单导出日期2".equals(itemName) ||"在购名单导出日期3".equals(itemName)) {
                        int value = Integer.parseInt(valueStr);
                        if (value < 1 || value > 12) {
                            return new ResultData("false","月份输入不合法,输入范围：1-12",null);
                        }
                    }
                }
            }
        }

        // 保存
        if (null != itaskDataModel && !itaskDataModel.isEmpty()) {
            for (Itask基础设置Model itaskModel : itaskDataModel) {
                itaskRepository.save(itaskModel);
            }
        }

        return new ResultData("true",null,null);
    }

    /**
     * 第三方精品的扩展金额  (四位小数的价格总和保留两位小数 - 两位小数的价格总和)
     * @param thirdBoutiques
     * @return
     */
    private BigDecimal getExpandAmtForBoutique(List<报价精品详细表Model> thirdBoutiques) {
        if (null == thirdBoutiques || thirdBoutiques.isEmpty()) {
            return new BigDecimal("0.00");
        }
        BigDecimal sum1 = new BigDecimal("0"); // 四位小数的精品价格总和
        BigDecimal sum2 = new BigDecimal("0"); // 两位小数的精品价格总和
        for (报价精品详细表Model model : thirdBoutiques ) {
            Integer number = model.get数量();
            BigDecimal price1 = model.get折后价(); // 四位小数的价格
            BigDecimal price2 = price1.setScale(2,BigDecimal.ROUND_HALF_UP);
            sum1 = sum1.add(price1.multiply(new BigDecimal(number)));
            sum2 = sum2.add(price2.multiply(new BigDecimal(number)));
        }
        sum1 = sum1.setScale(2,BigDecimal.ROUND_HALF_UP);  // 保留两位小数
        return sum1.subtract(sum2);
    }
}
